'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 { useTheme } from '@mui/material/styles'

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

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

interface HeatmapDataPoint {
  x: string
  y: number
}

interface HeatmapSeries {
  name: string
  data: HeatmapDataPoint[]
}

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

const SoilMoistureHeatmap = ({ data }: SoilMoistureHeatmapProps) => {
  const t = useTranslations('farmDashboard')
  const series = (data?.series as HeatmapSeries[]) ?? []
  const theme = useTheme()
  if (series.length === 0) return null

  const options: ApexOptions = {
    chart: {
      parentHeightOffset: 0,
      toolbar: { show: false }
    },
    dataLabels: { enabled: false },
    legend: {
      position: 'bottom',
      labels: { colors: 'var(--mui-palette-text-secondary)' },
      markers: { offsetX: theme.direction === 'rtl' ? 7 : -4 }
    },
    plotOptions: {
      heatmap: {
        enableShades: false,
        colorScale: {
          ranges: [
            { from: 0, to: 30, name: t('colorScale.low'), color: '#ff6b6b' },
            { from: 31, to: 50, name: t('colorScale.moderate'), color: '#ffd93d' },
            { from: 51, to: 70, name: t('colorScale.optimal'), color: '#6bcb77' },
            { from: 71, to: 100, name: t('colorScale.high'), color: '#4d96ff' }
          ]
        }
      }
    },
    grid: { padding: { top: -20 } },
    xaxis: {
      labels: { show: true, style: { colors: 'var(--mui-palette-text-disabled)', fontSize: '11px' } }
    },
    yaxis: {
      labels: {
        style: { colors: 'var(--mui-palette-text-disabled)', fontSize: '13px' }
      }
    }
  }

  return (
    <Card>
      <CardHeader
        title={t('cards.soilMoistureHeatmap')}
        subheader={t('subheaders.fieldZonesByTime')}
      />
      <CardContent>
        <AppReactApexCharts type='heatmap' width='100%' height={350} options={options} series={series} />
      </CardContent>
    </Card>
  )
}

export default SoilMoistureHeatmap
