'use client'

// React Imports
import { useEffect, useState } from 'react'

// MUI Imports
import Grid from '@mui/material/Grid2'
import Box from '@mui/material/Box'
import CircularProgress from '@mui/material/CircularProgress'

// Component Imports
import FarmWeatherCard from '@views/dashboards/farm/FarmWeatherCard'
import FarmAlertsTimeline from '@views/dashboards/farm/FarmAlertsTimeline'
import WaterNeedPrediction from '@views/dashboards/farm/WaterNeedPrediction'
import SensorValuesList from '@views/dashboards/farm/SensorValuesList'

// Service
import { farmDashboardService } from '@/libs/api/services/farmDashboardService'
import type { CardId } from '@views/dashboards/farm/farmDashboardConfig'

/** هر ردیف: آرایهٔ کارت‌ها؛ در هر ردیف فضا مساوی بین گریدها تقسیم می‌شود (جمع = ۱۲) */
const WATER_ROWS: CardId[][] = [
  ['farmWeatherCard', 'farmAlertsTimeline', 'waterNeedPrediction'],
  ['sensorValuesList']
]

const cardRowSx = {
  display: 'flex',
  flexDirection: 'column',
  minHeight: 380,
  '& > *': { flex: 1, minHeight: 0 }
}

const CARD_COMPONENTS: Partial<Record<CardId, React.ComponentType<{ data?: Record<string, unknown> }>>> = {
  farmWeatherCard: FarmWeatherCard,
  farmAlertsTimeline: FarmAlertsTimeline,
  waterNeedPrediction: WaterNeedPrediction,
  sensorValuesList: SensorValuesList
}

const WaterDataDashboardWrapper = () => {
  const [cardsData, setCardsData] = useState<Partial<Record<CardId, Record<string, unknown>>>>({})
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    farmDashboardService
      .getAllCards()
      .then(cards => setCardsData(cards ?? {}))
      .catch(() => setCardsData({}))
      .finally(() => setLoading(false))
  }, [])

  if (loading) {
    return (
      <Box display='flex' justifyContent='center' alignItems='center' minHeight={200}>
        <CircularProgress />
      </Box>
    )
  }

  return (
    <Box position='relative'>
      <Grid container spacing={6}>
        {WATER_ROWS.map((rowCards, rowIndex) => {
          const sizePerCard = 12 / rowCards.length
          return (
            <Grid
              key={rowIndex}
              size={12}
              container
              spacing={6}
              sx={{ display: 'flex', alignItems: 'stretch' }}
            >
              {rowCards.map(cardId => {
                const Component = CARD_COMPONENTS[cardId]
                if (!Component) return null
                return (
                  <Grid key={cardId} size={sizePerCard} sx={cardRowSx}>
                    <Component data={cardsData?.[cardId]} />
                  </Grid>
                )
              })}
            </Grid>
          )
        })}
      </Grid>
    </Box>
  )
}

export default WaterDataDashboardWrapper
