'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 SoilMoistureHeatmap from '@views/dashboards/farm/SoilMoistureHeatmap'
import SensorValuesList from '@views/dashboards/farm/SensorValuesList'
import SensorComparisonChart from '@views/dashboards/farm/SensorComparisonChart'
import SensorRadarChart from '@views/dashboards/farm/SensorRadarChart'
import AnomalyDetectionCard from '@views/dashboards/farm/AnomalyDetectionCard'

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

const SOIL_CARD_IDS: CardId[] = [
  'soilMoistureHeatmap',
  'sensorValuesList',
  'sensorRadarChart',
  'sensorComparisonChart',
  'anomalyDetectionCard'
]

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

const CARD_COMPONENTS: Partial<Record<CardId, React.ComponentType<{ data?: Record<string, unknown> }>>> = {
  soilMoistureHeatmap: SoilMoistureHeatmap,
  sensorValuesList: SensorValuesList,
  sensorComparisonChart: SensorComparisonChart,
  sensorRadarChart: SensorRadarChart,
  anomalyDetectionCard: AnomalyDetectionCard
}

const SoilDataDashboardWrapper = () => {
  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}>
        <Grid size={12} container spacing={6} sx={{ display: 'flex', alignItems: 'flex-start' }}>
          {SOIL_CARD_IDS.map(cardId => {
            const size = CARD_GRID_SIZE[cardId]
            const Component = CARD_COMPONENTS[cardId]
            if (!Component) return null
            return (
              <Grid key={cardId} size={size} sx={cardRowSx}>
                <Component data={cardsData?.[cardId]} />
              </Grid>
            )
          })}
        </Grid>
      </Grid>
    </Box>
  )
}

export default SoilDataDashboardWrapper
