'use client'

// Next Imports
import dynamic from 'next/dynamic'
import { useTranslations } from 'next-intl'

// MUI Imports
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import CardContent from '@mui/material/CardContent'
import Typography from '@mui/material/Typography'
import { useTheme } from '@mui/material/styles'

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

// Component Imports
import OptionMenu from '@core/components/option-menu'
import CustomAvatar from '@core/components/mui/Avatar'

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

type SummaryItem = {
  title: string
  subtitle: string
  amount: string
  avatarColor: string
  avatarIcon: string
}

interface YieldPredictionChartProps {
  data?: Record<string, unknown>
}

const YieldPredictionChart = ({ data }: YieldPredictionChartProps) => {
  const t = useTranslations('farmDashboard')
  const series = (data?.series as Array<{ name: string; data: number[] }>) ?? []
  const categories =
    (data?.categories as string[]) ??
    [
      t('fallback.monthJan'),
      t('fallback.monthFeb'),
      t('fallback.monthMar'),
      t('fallback.monthApr'),
      t('fallback.monthMay'),
      t('fallback.monthJun'),
      t('fallback.monthJul'),
      t('fallback.monthAug'),
      t('fallback.monthSep'),
      t('fallback.monthOct'),
      t('fallback.monthNov'),
      t('fallback.monthDec')
    ]
  const summary = (data?.summary as SummaryItem[]) ?? []
  const theme = useTheme()
  if (series.length === 0) return null

  const options: ApexOptions = {
    chart: {
      stacked: false,
      parentHeightOffset: 0,
      toolbar: { show: false }
    },
    legend: {
      position: 'top',
      labels: { colors: 'var(--mui-palette-text-secondary)' }
    },
    stroke: { width: 2, curve: 'smooth' },
    colors: ['var(--mui-palette-primary-main)', 'var(--mui-palette-success-main)'],
    dataLabels: { enabled: false },
    grid: {
      borderColor: 'var(--mui-palette-divider)',
      strokeDashArray: 4
    },
    xaxis: {
      categories,
      labels: { style: { colors: 'var(--mui-palette-text-disabled)' } }
    },
    yaxis: {
      labels: {
        style: { colors: 'var(--mui-palette-text-disabled)' },
        formatter: (val: number) => `${val} ${t('labels.tons')}`
      }
    },
    tooltip: {
      y: { formatter: (val: number) => `${val} ${t('labels.tons')}` }
    }
  }

  return (
    <Card>
      <CardHeader
        title={t('cards.yieldPredictionChart')}
        subheader={t('subheaders.thisYearVsLastYear')}
        action={<OptionMenu options={[t('optionMenu.export'), t('optionMenu.compare'), t('optionMenu.details')]} />}
      />
      <CardContent className='flex flex-col gap-4'>
        <AppReactApexCharts type='line' height={280} width='100%' series={series} options={options} />
        {summary.length > 0 && (
          <div className='flex flex-col gap-4'>
            {summary.map((item, index) => (
              <div key={index} className='flex items-center gap-4'>
                <CustomAvatar skin='light' variant='rounded' color={item.avatarColor as 'primary'} size={38}>
                  <i className={classnames(item.avatarIcon, 'text-[22px]')} />
                </CustomAvatar>
                <div className='flex justify-between items-center is-full'>
                  <div className='flex flex-col'>
                    <Typography className='font-medium' color='text.primary'>
                      {item.title}
                    </Typography>
                    <Typography variant='body2'>{item.subtitle}</Typography>
                  </div>
                  <Typography className='font-medium' color='success.main'>
                    {item.amount}
                  </Typography>
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  )
}

export default YieldPredictionChart
