'use client'

import { useTranslations } from 'next-intl'
import useMediaQuery from '@mui/material/useMediaQuery'
import { useTheme } from '@mui/material/styles'
import Drawer from '@mui/material/Drawer'
import Typography from '@mui/material/Typography'
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'

// Component Imports
import PerfectScrollbar from 'react-perfect-scrollbar'
import Select from '@mui/material/Select'
import MenuItem from '@mui/material/MenuItem'
import FormControl from '@mui/material/FormControl'
import InputLabel from '@mui/material/InputLabel'
import CircularProgress from '@mui/material/CircularProgress'
import {
  Radar,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  ResponsiveContainer
} from 'recharts'
import { CROP_COLORS } from './cropZoningTypes'
import type { Product } from '@/libs/api/services/cropZoningService'
import type { ZoneDetailData } from '@/libs/api/services/cropZoningService'

type ZoneDetailPanelProps = {
  open: boolean
  onClose: () => void
  zone: ZoneDetailData | null
  products?: Product[]
  loading?: boolean
  onCropChange?: (zoneId: string, crop: string) => void
}

const FALLBACK_LABELS: Record<string, string> = {
  wheat: 'گندم',
  canola: 'کلزا',
  saffron: 'زعفران'
}

export default function ZoneDetailPanel({
  open,
  onClose,
  zone,
  products = [],
  loading = false,
  onCropChange
}: ZoneDetailPanelProps) {
  const t = useTranslations('cropZoning')
  const tCommon = useTranslations('common')
  const theme = useTheme()
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'))

  const cropLabels = products.length > 0
    ? Object.fromEntries(products.map(p => [p.id, p.label]))
    : FALLBACK_LABELS

  if (!open) return null

  const chartData = zone?.criteria?.map(c => ({ subject: c.name, value: c.value, fullMark: 100 })) ?? []

  return (
    <Drawer
      open={open}
      onClose={onClose}
      anchor='right'
      variant='temporary'
      ModalProps={{
        disablePortal: true,
        disableAutoFocus: true,
        keepMounted: true
      }}
      PaperProps={{
        className: isMobile ? 'is-full max-is-[100vw]' : 'is-[360px] max-is-[100vw] rounded-s-xl shadow-xl border-s border-gray-200/50 dark:border-gray-700/50',
        sx: { bgcolor: 'background.paper' }
      }}
      sx={{ zIndex: 1300 }}
    >
      <Box className='flex flex-col is-full' sx={{ height: '100%' }}>
        <Box className='p-6 pb-2'>
          <Typography variant='h5'>
            {t('panel.title')}
          </Typography>
        </Box>
        <PerfectScrollbar options={{ wheelPropagation: false }} className='flex-1 px-6 pb-6'>
        <Box className='flex flex-col gap-4'>
          {loading ? (
            <Box className='flex justify-center py-12'>
              <CircularProgress />
            </Box>
          ) : zone ? (
            <>
              <Box className='rounded-xl border border-gray-200/60 dark:border-gray-700/60 p-4 bg-white/50 dark:bg-gray-800/30'>
                <Typography variant='subtitle2' color='text.secondary' className='mbe-2'>
                  محصول پیشنهادی
                </Typography>
                <Typography variant='h6' sx={{ color: CROP_COLORS[zone.crop as keyof typeof CROP_COLORS] ?? undefined }}>
                  {cropLabels[zone.crop] ?? zone.crop}
                </Typography>
                <Typography variant='body2' className='mt-2'>
                  درصد تطابق: {zone.matchPercent}%
                </Typography>
                <Typography variant='body2'>نیاز آب: {zone.waterNeed}</Typography>
                <Typography variant='body2'>سود تخمینی: {zone.estimatedProfit}</Typography>
              </Box>

              <Box>
                <Typography variant='subtitle2' color='text.secondary' className='mbe-2'>
                  {t('panel.reason')}
                </Typography>
                <Typography variant='body2'>{zone.reason}</Typography>
              </Box>

              {chartData.length > 0 && (
                <Box className='rounded-xl border border-gray-200/60 dark:border-gray-700/60 p-4 bg-white/50 dark:bg-gray-800/30'>
                  <Typography variant='subtitle2' color='text.secondary' className='mbe-3'>
                    {t('panel.criteriaChart')}
                  </Typography>
                  <div className='bs-[220px]'>
                    <ResponsiveContainer width='100%' height='100%'>
                      <RadarChart data={chartData}>
                        <PolarGrid />
                        <PolarAngleAxis dataKey='subject' />
                        <PolarRadiusAxis angle={90} domain={[0, 100]} />
                        <Radar
                          name='امتیاز'
                          dataKey='value'
                          stroke='var(--mui-palette-primary-main)'
                          fill='var(--mui-palette-primary-main)'
                          fillOpacity={0.4}
                          strokeWidth={2}
                        />
                      </RadarChart>
                    </ResponsiveContainer>
                  </div>
                </Box>
              )}

              <FormControl fullWidth size='small'>
                <InputLabel>{t('panel.changeCrop')}</InputLabel>
                <Select
                  value={zone.crop}
                  label={t('panel.changeCrop')}
                  onChange={e => onCropChange?.(zone.zoneId, e.target.value)}
                >
                  {products.length > 0
                    ? products.map(p => (
                        <MenuItem key={p.id} value={p.id}>
                          {p.label}
                        </MenuItem>
                      ))
                    : Object.entries(FALLBACK_LABELS).map(([id, label]) => (
                        <MenuItem key={id} value={id}>
                          {label}
                        </MenuItem>
                      ))}
                </Select>
              </FormControl>
            </>
          ) : (
            <Typography variant='body2' color='text.secondary'>
              اطلاعاتی یافت نشد.
            </Typography>
          )}

          <Button variant='outlined' onClick={onClose} fullWidth>
            {tCommon('close')}
          </Button>
        </Box>
        </PerfectScrollbar>
      </Box>
    </Drawer>
  )
}
