'use client'

import { useState, useEffect } from 'react'
import { useTranslations } from 'next-intl'
import Box from '@mui/material/Box'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import IconButton from '@mui/material/IconButton'
import CircularProgress from '@mui/material/CircularProgress'
import { useTheme, alpha } from '@mui/material/styles'
import type { FarmInfo, CropOption, IrrigationPlan } from '@/libs/api/services/irrigationRecommendationService'
import { irrigationRecommendationService } from '@/libs/api/services/irrigationRecommendationService'

const DEFAULT_FARM_INFO: FarmInfo = {
  soilType: 'Loamy',
  waterQuality: 'Medium EC',
  climateZone: 'Temperate'
}

export default function SmartIrrigationRecommendation() {
  const t = useTranslations('irrigation')
  const theme = useTheme()
  const [farmInfo, setFarmInfo] = useState<FarmInfo>(DEFAULT_FARM_INFO)
  const [cropOptions, setCropOptions] = useState<CropOption[]>([])
  const [configLoading, setConfigLoading] = useState(true)
  const [configError, setConfigError] = useState<string | null>(null)
  const [selectedCrop, setSelectedCrop] = useState<string | null>(null)
  const [plan, setPlan] = useState<IrrigationPlan | null>(null)
  const [loading, setLoading] = useState(false)
  const primaryMain = theme.palette.primary.main
  const primaryLight = theme.palette.primary.light
  const primaryDark = theme.palette.primary.dark
  const paperBg = theme.palette.background.paper

  useEffect(() => {
    irrigationRecommendationService
      .getConfig()
      .then(({ farmInfo: info, cropOptions: crops }) => {
        setFarmInfo(info)
        setCropOptions(crops.length > 0 ? crops : [])
      })
      .catch((err: { message?: string }) => {
        setConfigError(err?.message ?? 'Failed to load config')
      })
      .finally(() => setConfigLoading(false))
  }, [])

  const handleGenerate = async () => {
    if (!selectedCrop) return
    setLoading(true)
    setPlan(null)
    try {
      const { plan: nextPlan } = await irrigationRecommendationService.recommend({
        crop_id: selectedCrop,
      })
      setPlan(nextPlan)
    } catch {
      setPlan(null)
    } finally {
      setLoading(false)
    }
  }

  return (
    <Box
      className='min-bs-screen'
      sx={{
        background: (theme) =>
          `linear-gradient(165deg, ${alpha(theme.palette.primary.main, 0.08)} 0%, ${alpha(theme.palette.primary.main, 0.04)} 35%, ${alpha(theme.palette.primary.main, 0.02)} 70%, ${theme.palette.background.default} 100%)`,
        minHeight: '100vh'
      }}
    >
      <Box className='max-w-lg mx-auto px-4 py-6 sm:py-8'>
        {/* 1) Dynamic Header */}
        <Box className='mb-8'>
          <Typography
            variant='h4'
            className='font-bold tracking-tight'
            sx={{
              background: `linear-gradient(135deg, ${primaryLight} 0%, ${primaryMain} 50%, ${primaryDark} 100%)`,
              backgroundClip: 'text',
              WebkitBackgroundClip: 'text',
              color: 'transparent',
              fontSize: { xs: '1.5rem', sm: '1.75rem' }
            }}
          >
            {t('title')}
          </Typography>
          <Typography variant='body2' color='text.secondary' className='mt-1'>
            {t('subtitle')}
          </Typography>
        </Box>

        {/* 2) Farm Info Card */}
        <Card
          elevation={0}
          className='mb-6 overflow-hidden transition-all duration-300 hover:shadow-lg'
          sx={{
            borderRadius: '24px',
            background: `linear-gradient(145deg, ${paperBg} 0%, ${alpha(primaryMain, 0.04)} 100%)`,
            boxShadow: `0 4px 24px ${alpha(primaryMain, 0.08)}, 0 1px 3px rgba(0,0,0,0.04)`,
            border: `1px solid ${alpha(primaryMain, 0.12)}`
          }}
        >
          <CardContent className='p-5'>
            <Box className='flex items-center justify-between mbe-4'>
              <Typography variant='subtitle2' fontWeight={600} color='text.secondary'>
                {t('farmInfo.title')}
              </Typography>
              <Box className='flex items-center gap-2'>
                <Box
                  className='px-2.5 py-1 rounded-full text-xs font-medium'
                  sx={{
                    background: (t) => `linear-gradient(135deg, ${t.palette.success.main} 0%, ${t.palette.success.dark} 100%)`,
                    color: 'white',
                    display: 'flex',
                    alignItems: 'center',
                    gap: 4
                  }}
                >
                  <i className='tabler-circle-check text-sm' />
                  {t('verifiedBadge')}
                </Box>
                <IconButton size='small' sx={{ color: 'text.secondary' }} aria-label={t('editFarmInfo')}>
                  <i className='tabler-pencil text-lg' />
                </IconButton>
              </Box>
            </Box>
            <Box className='flex flex-wrap gap-3'>
              <FarmBadge icon='tabler-seedling' label={t('farmInfo.soilType')} value={farmInfo.soilType} />
              <FarmBadge icon='tabler-droplet' label={t('farmInfo.waterQuality')} value={farmInfo.waterQuality} />
              <FarmBadge icon='tabler-temperature' label={t('farmInfo.climateZone')} value={farmInfo.climateZone} />
            </Box>
          </CardContent>
        </Card>

        {/* 3) Plant Selection Section */}
        <Typography variant='subtitle2' fontWeight={600} color='text.secondary' className='mbe-3'>
          {t('plantSelection.title')}
        </Typography>
        {configLoading ? (
          <Box className='flex justify-center py-8'>
            <CircularProgress size={32} sx={{ color: 'primary.main' }} />
          </Box>
        ) : configError ? (
          <Typography variant='body2' color='error' className='mb-6'>
            {configError}
          </Typography>
        ) : (
        <Box className='flex flex-wrap gap-3 mb-6'>
          {(cropOptions.length > 0 ? cropOptions : []).map(crop => (
            <CropCard
              key={crop.id}
              crop={crop}
              label={t(`crops.${crop.labelKey}`)}
              selected={selectedCrop === crop.id}
              onClick={() => setSelectedCrop(prev => (prev === crop.id ? null : crop.id))}
            />
          ))}
        </Box>
        )}

        {/* 4) Primary CTA Button - End of form */}
        <Box className='mb-8'>
          <Button
            fullWidth
            variant='contained'
            disabled={!selectedCrop || loading || configLoading}
            onClick={handleGenerate}
            startIcon={<i className='tabler-sparkles text-xl' />}
            className='rounded-2xl py-3.5 text-base font-semibold shadow-lg transition-all duration-300 hover:shadow-xl hover:scale-[1.01] active:scale-[0.99]'
            sx={{
              background: `linear-gradient(135deg, ${primaryLight} 0%, ${primaryMain} 50%, ${primaryDark} 100%)`,
              boxShadow: `0 4px 20px ${alpha(primaryMain, 0.4)}`,
              '&:hover': {
                background: `linear-gradient(135deg, ${primaryLight} 0%, ${primaryMain} 50%, ${primaryDark} 100%)`,
                boxShadow: `0 6px 28px ${alpha(primaryMain, 0.5)}`,
                filter: 'brightness(1.05)'
              },
              '&:disabled': {
                background: 'action.disabledBackground',
                color: 'action.disabled'
              }
            }}
          >
            {t('generateCta')}
          </Button>
        </Box>

        {/* 5) Result Card (after click) */}
        {plan && (
          <Box className='mb-6 animate-fade-in'>
            <Card
              elevation={0}
              sx={{
                borderRadius: '24px',
                background: `linear-gradient(160deg, ${paperBg} 0%, ${alpha(primaryMain, 0.06)} 100%)`,
                boxShadow: `0 8px 32px ${alpha(primaryMain, 0.15)}, 0 2px 8px rgba(0,0,0,0.06)`,
                border: `1px solid ${alpha(primaryMain, 0.18)}`,
                overflow: 'visible'
              }}
            >
              <CardContent className='p-6'>
                {/* Circular moisture indicator */}
                <Box className='flex justify-center mbe-6'>
                  <Box className='relative'>
                    <svg width={120} height={120} className='-rotate-90'>
                      <circle
                        cx={60}
                        cy={60}
                        r={52}
                        fill='none'
                        stroke={alpha(primaryMain, 0.12)}
                        strokeWidth={10}
                      />
                      <circle
                        cx={60}
                        cy={60}
                        r={52}
                        fill='none'
                        stroke='url(#moistureGradient)'
                        strokeWidth={10}
                        strokeLinecap='round'
                        strokeDasharray={`${(plan.moistureLevel / 100) * 327} 327`}
                        className='transition-all duration-1000 ease-out'
                      />
                      <defs>
                        <linearGradient id='moistureGradient' x1='0%' y1='0%' x2='100%' y2='100%'>
                          <stop offset='0%' stopColor={primaryLight} />
                          <stop offset='100%' stopColor={primaryMain} />
                        </linearGradient>
                      </defs>
                    </svg>
                    <Box
                      className='absolute inset-0 flex flex-col items-center justify-center'
                      sx={{ top: 0, left: 0, right: 0, bottom: 0 }}
                    >
                      <i className='tabler-droplet text-3xl mbe-0.5' style={{ color: primaryMain }} />
                      <Typography variant='h4' fontWeight={700} color='primary.main'>
                        {plan.moistureLevel}%
                      </Typography>
                      <Typography variant='caption' color='text.secondary'>
                        {t('result.moistureLevel')}
                      </Typography>
                    </Box>
                  </Box>
                </Box>

                <Box className='space-y-4'>
                  <ResultRow
                    icon='tabler-calendar-week'
                    label={t('result.frequency')}
                    value={`${plan.frequencyPerWeek} ${t('result.timesPerWeek')}`}
                  />
                  <ResultRow
                    icon='tabler-clock'
                    label={t('result.duration')}
                    value={`${plan.durationMinutes} ${t('result.minutes')}`}
                  />
                  <ResultRow
                    icon='tabler-sunrise'
                    label={t('result.bestTime')}
                    value={plan.bestTimeOfDay}
                  />
                </Box>

                {plan.warning && (
                  <Box
                    className='mt-4 p-4 rounded-2xl'
                    sx={{
                      background: 'linear-gradient(135deg, rgba(251, 191, 36, 0.12) 0%, rgba(245, 158, 11, 0.08) 100%)',
                      border: '1px solid rgba(251, 191, 36, 0.35)'
                    }}
                  >
                    <Box className='flex gap-2'>
                      <i className='tabler-alert-triangle text-xl text-amber-600 mt-0.5 shrink-0' />
                      <Box>
                        <Typography variant='subtitle2' fontWeight={600} color='warning.dark' className='mbe-1'>
                          {t('result.smartWarning')}
                        </Typography>
                        <Typography variant='body2' color='text.secondary'>
                          {plan.warning}
                        </Typography>
                      </Box>
                    </Box>
                  </Box>
                )}
              </CardContent>
            </Card>
          </Box>
        )}

        {/* Loading state */}
        {loading && (
          <Card
            elevation={0}
            className='mb-6'
            sx={{
              borderRadius: '24px',
              background: `linear-gradient(160deg, ${paperBg} 0%, ${alpha(primaryMain, 0.06)} 100%)`,
              boxShadow: `0 8px 32px ${alpha(primaryMain, 0.1)}`,
              border: `1px solid ${alpha(primaryMain, 0.12)}`
            }}
          >
            <CardContent className='p-12 flex flex-col items-center gap-4'>
              <CircularProgress size={48} sx={{ color: 'primary.main' }} />
              <Typography variant='body2' color='text.secondary'>
                {t('generating')}
              </Typography>
            </CardContent>
          </Card>
        )}
      </Box>
    </Box>
  )
}

// ─── Sub-components ──────────────────────────────────────────────────────────

function FarmBadge({
  icon,
  label,
  value
}: {
  icon: string
  label: string
  value: string
}) {
  const theme = useTheme()
  const primaryMain = theme.palette.primary.main
  return (
    <Box
      className='flex items-center gap-2 px-4 py-2.5 rounded-2xl transition-transform duration-200 hover:scale-[1.02]'
      sx={{
        background: `linear-gradient(145deg, ${alpha(primaryMain, 0.08)} 0%, ${alpha(primaryMain, 0.04)} 100%)`,
        border: `1px solid ${alpha(primaryMain, 0.15)}`,
        boxShadow: 'inset 0 1px 2px rgba(255,255,255,0.5)'
      }}
    >
      <i className={`${icon} text-xl`} style={{ color: primaryMain }} />
      <Box>
        <Typography variant='caption' color='text.secondary' display='block' lineHeight={1.2}>
          {label}
        </Typography>
        <Typography variant='body2' fontWeight={600} color='text.primary'>
          {value}
        </Typography>
      </Box>
    </Box>
  )
}

function CropCard({
  crop,
  label,
  selected,
  onClick
}: {
  crop: CropOption
  label: string
  selected: boolean
  onClick: () => void
}) {
  const theme = useTheme()
  const primaryMain = theme.palette.primary.main
  const primaryDark = theme.palette.primary.dark
  const paperBg = theme.palette.background.paper
  return (
    <Card
      component='button'
      type='button'
      elevation={0}
      onClick={onClick}
      className='flex items-center gap-3 px-4 py-3 rounded-2xl cursor-pointer transition-all duration-300 border-2 text-start'
      sx={{
        borderColor: selected ? primaryMain : 'transparent',
        background: selected
          ? `linear-gradient(145deg, ${alpha(primaryMain, 0.12)} 0%, ${alpha(primaryMain, 0.06)} 100%)`
          : `linear-gradient(145deg, ${paperBg} 0%, ${alpha(primaryMain, 0.04)} 100%)`,
        boxShadow: selected
          ? `0 4px 20px ${alpha(primaryMain, 0.2)}, inset 0 1px 0 rgba(255,255,255,0.8)`
          : '0 2px 8px rgba(0,0,0,0.04), inset 0 1px 0 rgba(255,255,255,0.9)',
        '&:hover': {
          transform: 'translateY(-2px)',
          boxShadow: selected
            ? `0 6px 24px ${alpha(primaryMain, 0.25)}`
            : `0 4px 16px ${alpha(primaryMain, 0.12)}`
        }
      }}
    >
      <Box
        className='w-11 h-11 rounded-xl flex items-center justify-center shrink-0'
        sx={{
          background: selected
            ? `linear-gradient(135deg, ${primaryMain} 0%, ${primaryDark} 100%)`
            : `linear-gradient(145deg, ${alpha(primaryMain, 0.1)} 0%, ${alpha(primaryMain, 0.05)} 100%)`
        }}
      >
        <i className={`${crop.icon} text-xl ${selected ? 'text-white' : ''}`} style={!selected ? { color: primaryMain } : undefined} />
      </Box>
      <Typography variant='body2' fontWeight={600} color={selected ? 'primary.main' : 'text.primary'}>
        {label}
      </Typography>
      {selected && (
        <i className='tabler-circle-check-filled text-xl ms-auto' style={{ color: primaryMain }} />
      )}
    </Card>
  )
}

function ResultRow({
  icon,
  label,
  value
}: {
  icon: string
  label: string
  value: string
}) {
  const theme = useTheme()
  const primaryMain = theme.palette.primary.main
  return (
    <Box className='flex items-center gap-4 p-3 rounded-2xl' sx={{ bgcolor: alpha(primaryMain, 0.06) }}>
      <i className={`${icon} text-2xl shrink-0`} style={{ color: primaryMain }} />
      <Box className='flex-1 min-w-0'>
        <Typography variant='caption' color='text.secondary'>
          {label}
        </Typography>
        <Typography variant='body1' fontWeight={600} color='text.primary'>
          {value}
        </Typography>
      </Box>
    </Box>
  )
}
