"use client";
import { ApexOptions } from "apexcharts";
import dynamic from "next/dynamic";
import { useState, useEffect } from "react";
import Image from 'next/image';

const ReactApexChart = dynamic(() => import("react-apexcharts"), {
  ssr: false,
});

export default function MonthlyChart() {
  const [chartData, setChartData] = useState<{ categories: string[], data: number[] }>({
    categories: [],
    data: []
  });
  const [allData, setAllData] = useState<any[]>([]);
  const [yearOptions, setYearOptions] = useState<string[]>([]);
  const [selectedYear, setSelectedYear] = useState<string>("");
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    async function fetchData() {
      try {
        const res = await fetch('/api/komoditas'); 
        if (!res.ok) throw new Error("Gagal mengambil data");
        
        const result = await res.json();
        
        if (Array.isArray(result)) {
          setAllData(result);

          const years = Array.from(new Set(result.map((item: any) => String(item.tahun_panen || item.tahun))))
            .filter(y => y !== "undefined" && y !== "null")
            .sort((a, b) => Number(b) - Number(a)); 

          setYearOptions(years);
          
          if (years.length > 0) {
            setSelectedYear(years[0]);
          }
        }
      } catch (error) {
        console.error("Error fetching chart data:", error);
      } finally {
        setIsLoading(false);
      }
    }

    fetchData();
  }, []);

  useEffect(() => {
    if (allData.length === 0 || !selectedYear) return;

    const filteredByYear = allData.filter((item: any) => 
      String(item.tahun_panen || item.tahun) === selectedYear
    );

    const aggregation: { [key: string]: number } = {};

    filteredByYear.forEach((item: any) => {
      const nama = item.nama_komoditas ? item.nama_komoditas.trim() : "Lainnya";
      const rawProduksi = item.produksi;
      let nilai = 0;

      if (typeof rawProduksi === 'string') {
         nilai = parseFloat(rawProduksi.replace(/\./g, '').replace(/,/g, '.')) || 0;
      } else {
         nilai = Number(rawProduksi) || 0;
      }

      if (nama) {
        aggregation[nama] = (aggregation[nama] || 0) + nilai;
      }
    });

    const keys = Object.keys(aggregation);
    const values = Object.values(aggregation).map(val => Number(val.toFixed(2)));

    setChartData({
      categories: keys,
      data: values
    });

  }, [selectedYear, allData]);

  const chartOptions: ApexOptions = {
    colors: ["#198f3f"], 
    chart: {
      fontFamily: "Outfit, sans-serif",
      type: "bar",
      height: 260, // TINGGI DIKECILKAN
      toolbar: { show: false },
    },
    plotOptions: {
      bar: {
        horizontal: false, 
        columnWidth: "50%",
        borderRadius: 4,
        dataLabels: {
            position: 'top', 
        },
      },
    },
    dataLabels: {
      enabled: false, 
      offsetY: -20,
      style: {
        fontSize: '12px',
        colors: ["#304758"]
      }
    },
    stroke: {
      show: true,
      width: 2,
      colors: ["transparent"],
    },
    xaxis: {
      categories: chartData.categories, 
      axisBorder: { show: true },
      axisTicks: { show: true },
      labels: {
        style: {
            fontSize: '12px',
            fontWeight: 500,
        },
        rotate: -45, 
        trim: false
      }
    },
    yaxis: {
      title: { 
        text: 'Produksi (Ton)',
        style: { fontWeight: 500 }
      },
      labels: {
        formatter: (value) => {
            if (value >= 1000000) return `${(value / 1000000).toFixed(1)}jt`;
            if (value >= 1000) return `${(value / 1000).toFixed(0)}k`;
            return value.toFixed(0);
        }
      }
    },
    grid: {
      strokeDashArray: 4,
      yaxis: { lines: { show: true } },
    },
    fill: { opacity: 1 },
    tooltip: {
      y: {
        formatter: (val: number) => `${val.toLocaleString('id-ID')} Ton`,
      },
    },
  };

  const chartSeries = [
    {
      name: "Total Produksi",
      data: chartData.data,
    },
  ];

  return (
    <div className="overflow-hidden rounded-2xl border border-gray-200 bg-white px-5 pt-5 dark:border-gray-800 dark:bg-white/[0.03] sm:px-6 sm:pt-6">
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-6">
        
        <div>
            <h3 className="text-lg font-semibold text-gray-800 dark:text-white/90">
            Statistik Komoditas
            </h3>
            <p className="text-sm text-gray-500">Total produksi berdasarkan tahun panen</p>
        </div>

        <div className="relative">
            <select 
                value={selectedYear}
                onChange={(e) => setSelectedYear(e.target.value)}
                className="appearance-none bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-green-500 focus:border-green-500 block w-32 p-2.5 pr-8 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white cursor-pointer"
                disabled={isLoading}
            >
                {yearOptions.map((year) => (
                    <option key={year} value={year}>{year}</option>
                ))}
                {yearOptions.length === 0 && <option disabled>No Data</option>}
            </select>
            
            <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700 dark:text-gray-300">
                <Image src="/icons/chevron-down.svg" width={16} height={16} alt="v" />
            </div>
        </div>

      </div>

      <div className="w-full">
          {isLoading ? (
             <div className="h-[260px] flex items-center justify-center text-gray-400 bg-gray-50 rounded-lg">
                Loading Grafik...
             </div>
          ) : chartData.categories.length > 0 ? (
            <ReactApexChart
                options={chartOptions}
                series={chartSeries}
                type="bar"
                height={260} /* TINGGI DIKECILKAN */
            />
          ) : (
            <div className="h-[260px] flex items-center justify-center text-gray-400 bg-gray-50 rounded-lg">
                Tidak ada data untuk tahun {selectedYear}
            </div>
          )}
      </div>
    </div>
  );
}