'use client'

import { useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import dynamic from 'next/dynamic'

// MUI Imports
import Box from '@mui/material/Box'
import Grid from '@mui/material/Grid2'
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import CardContent from '@mui/material/CardContent'
import Typography from '@mui/material/Typography'

// Third-party Imports
import type { ApexOptions } from 'apexcharts'

// Component Imports
import FarmWeatherCard from '@views/dashboards/farm/FarmWeatherCard'
import { farmDashboardService } from '@/libs/api/services/farmDashboardService'

// Styled Component Imports
const AppReactApexCharts = dynamic(() => import('@/libs/styles/AppReactApexCharts'))

const DEFAULT_WEATHER = {
  temperature: 24,
  condition: 'آفتابی',
  humidity: 45,
  windSpeed: 12,
  windUnit: 'km/h',
  unit: '°C',
  precipitation: 0
}

const DEFAULT_FORECAST_SERIES = [
  { name: 'دما', data: [18, 22, 26, 28, 25, 20, 18] },
  { name: 'رطوبت', data: [55, 48, 42, 38, 45, 52, 58] }
]

const FORECAST_CATEGORIES = ['امروز', 'فردا', 'شنبه', 'یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه']

export default function CropZoningWeatherSection() {
  const t = useTranslations('cropZoning.weather')
  const [weatherData, setWeatherData] = useState<Record<string, unknown>>(DEFAULT_WEATHER)
  const [forecastSeries, setForecastSeries] = useState(DEFAULT_FORECAST_SERIES)

  useEffect(() => {
    farmDashboardService
      .getAllCards()
      .then(cards => {
        const w = cards?.farmWeatherCard
        if (w && typeof w === 'object') {
          setWeatherData({ ...DEFAULT_WEATHER, ...w })
          const chartData = w.chartData as { labels?: string[]; series?: number[][] } | undefined
          if (chartData?.series?.[0]) {
            setForecastSeries([{ name: 'دما', data: chartData.series[0] }])
          }
        }
      })
      .catch(() => {})
  }, [])

  const forecastOptions: ApexOptions = {
    chart: {
      parentHeightOffset: 0,
      toolbar: { show: false },
      zoom: { enabled: false }
    },
    colors: ['var(--mui-palette-info-main)', 'var(--mui-palette-success-main)'],
    stroke: { width: 2, curve: 'smooth' },
    legend: {
      position: 'top',
      labels: { colors: 'var(--mui-palette-text-secondary)' }
    },
    dataLabels: { enabled: false },
    grid: {
      borderColor: 'var(--mui-palette-divider)',
      strokeDashArray: 4,
      xaxis: { lines: { show: false } },
      yaxis: { lines: { show: true } }
    },
    xaxis: {
      categories: FORECAST_CATEGORIES,
      labels: { style: { colors: 'var(--mui-palette-text-disabled)' } },
      axisBorder: { show: false },
      axisTicks: { show: false }
    },
    yaxis: {
      labels: {
        style: { colors: 'var(--mui-palette-text-disabled)' }
      }
    }
  }

  const temp = (weatherData.temperature as number) ?? 24
  const humidity = (weatherData.humidity as number) ?? 45
  const windSpeed = (weatherData.windSpeed as number) ?? 12

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

  return (
    <Box className='pis-0 pie-0'>
      <Typography variant='h6' className='mbe-4 font-semibold'>
        {t('title')}
      </Typography>
      <Grid container spacing={3}>
        {/* Row 1: Weather + 3 KPI cards — equal width (3 each on md+) */}
        <Grid
          size={12}
          container
          spacing={3}
          sx={{ display: 'flex', alignItems: 'stretch' }}
        >
          <Grid size={{ xs: 12, md: 3 }} sx={cardRowSx}>
            <FarmWeatherCard data={weatherData} />
          </Grid>
          <Grid size={{ xs: 12, sm: 4, md: 3 }} sx={cardRowSx}>
            <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
              <CardContent className='flex flex-1 flex-col items-center justify-center gap-2'>
                <i className='tabler-temperature text-3xl text-error' />
                <Typography variant='body2' color='text.secondary'>
                  {t('temperature')}
                </Typography>
                <Typography variant='h5'>
                  {temp}
                  {(weatherData.unit as string) ?? '°C'}
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          <Grid size={{ xs: 12, sm: 4, md: 3 }} sx={cardRowSx}>
            <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
              <CardContent className='flex flex-1 flex-col items-center justify-center gap-2'>
                <i className='tabler-droplet text-3xl text-info' />
                <Typography variant='body2' color='text.secondary'>
                  {t('humidity')}
                </Typography>
                <Typography variant='h5'>{humidity}%</Typography>
              </CardContent>
            </Card>
          </Grid>
          <Grid size={{ xs: 12, sm: 4, md: 3 }} sx={cardRowSx}>
            <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
              <CardContent className='flex flex-1 flex-col items-center justify-center gap-2'>
                <i className='tabler-wind text-3xl text-success' />
                <Typography variant='body2' color='text.secondary'>
                  {t('windSpeed')}
                </Typography>
                <Typography variant='h5'>
                  {windSpeed} {(weatherData.windUnit as string) ?? 'km/h'}
                </Typography>
              </CardContent>
            </Card>
          </Grid>
        </Grid>

        {/* Row 2: Forecast chart — full width */}
        <Grid size={12} sx={cardRowSx}>
          <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column', minHeight: 280 }}>
            <CardHeader
              title={t('forecastChart')}
              subheader={t('forecastSubheader')}
            />
            <CardContent sx={{ flex: 1, minHeight: 0 }}>
              <AppReactApexCharts
                type='line'
                height={260}
                width='100%'
                series={forecastSeries}
                options={forecastOptions}
              />
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </Box>
  )
}
