'use client';

import { useEffect, useState } from 'react';
import dynamic from 'next/dynamic';
import { ApexOptions } from 'apexcharts';
import { useTheme } from 'next-themes';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

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

interface NamaBeasiswaPerAngkatanData {
  nama_beasiswa: string;
  jumlah_nama_beasiswa: number;
}

interface Props {
  selectedYear: string;
}

export default function NamaBeasiswaDashPieChartPerangkatan({ selectedYear }: Props) {
  const { theme } = useTheme();
  const [data, setData] = useState<NamaBeasiswaPerAngkatanData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        setError(null);
        
        const url = `/api/mahasiswa/nama-beasiswa-dashboard?tahunAngkatan=${selectedYear}`;
        
        const response = await fetch(url);
        
        if (!response.ok) {
          throw new Error(`Failed to fetch data: ${response.status} ${response.statusText}`);
        }
        
        const result = await response.json();
        
        if (!Array.isArray(result)) {
          throw new Error('Invalid data format received from server');
        }
        
        // Filter data for selected year and group by nama_beasiswa
        const yearData = result.filter((item: any) => 
          item.tahun_angkatan.toString() === selectedYear
        );
        
        // Group by nama_beasiswa and sum jumlah_nama_beasiswa
        const groupedData = yearData.reduce((acc: { [key: string]: number }, item: any) => {
          const namaBeasiswa = item.nama_beasiswa || 'Tidak Diketahui';
          acc[namaBeasiswa] = (acc[namaBeasiswa] || 0) + item.jumlah_nama_beasiswa;
          return acc;
        }, {});

        // Convert to array format
        const chartData = Object.entries(groupedData).map(([nama_beasiswa, jumlah_nama_beasiswa]) => ({
          nama_beasiswa,
          jumlah_nama_beasiswa: jumlah_nama_beasiswa as number
        }));

        // Sort by jumlah_nama_beasiswa descending
        const sortedData = chartData.sort((a, b) => (b.jumlah_nama_beasiswa as number) - (a.jumlah_nama_beasiswa as number));
        setData(sortedData);
      } catch (err) {
        console.error('Error in fetchData:', err);
        setError(err instanceof Error ? err.message : 'An error occurred while fetching data');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [selectedYear]);

  // Prepare data for pie chart
  const series = data.map(item => item.jumlah_nama_beasiswa);
  const labels = data.map(item => item.nama_beasiswa);

  const chartOptions: ApexOptions = {
    chart: {
      type: 'pie',
      toolbar: {
        show: true,
        tools: {
          download: true,
          selection: true,
          zoom: true,
          zoomin: true,
          zoomout: true,
          pan: true,
          reset: true
        }
      },
      background: theme === 'dark' ? '#0F172B' : '#fff',
    },
    labels: labels,
    dataLabels: {
      enabled: true,
      formatter: function (val: number) {
        return `${val.toFixed(0)}%`;
      },
      style: {
        fontSize: '14px',
        fontFamily: 'Inter, sans-serif',
        fontWeight: '500'
      }
    },
    legend: {
      position: 'bottom',
      fontSize: '12px',
      markers: {
        size: 12,
      },
      itemMargin: {
        horizontal: 10,
        vertical: 5,
      },
      labels: {
        colors: theme === 'dark' ? '#fff' : '#000'
      }
    },
    colors: [
      '#3B82F6', // Blue
      '#EC4899', // Pink
      '#10B981', // Green
      '#F59E0B', // Yellow
      '#EF4444', // Red
      '#8B5CF6', // Purple
      '#06B6D4', // Cyan
      '#F97316', // Orange
      '#84CC16', // Lime
      '#06B6D4', // Teal
    ],
    tooltip: {
      theme: theme === 'dark' ? 'dark' : 'light',
      y: {
        formatter: function (val: number) {
          return val + ' mahasiswa';
        }
      }
    },
    plotOptions: {
      pie: {
        donut: {
          size: '0%',
        },
        offsetY: 0,
      },
    },
    states: {
      hover: {
        filter: {
          type: 'darken',
        },
      },
    },
  };

  if (loading) {
    return (
      <Card className="bg-white dark:bg-slate-900 shadow-lg">
        <CardHeader>
          <CardTitle className="text-xl font-bold dark:text-white">
            Loading...
          </CardTitle>
        </CardHeader>
      </Card>
    );
  }

  if (error) {
    return (
      <Card className="bg-white dark:bg-slate-900 shadow-lg">
        <CardHeader>
          <CardTitle className="text-xl font-bold text-red-500">
            Error: {error}
          </CardTitle>
        </CardHeader>
      </Card>
    );
  }

  if (data.length === 0) {
    return (
      <Card className="bg-white dark:bg-slate-900 shadow-lg">
        <CardHeader>
          <CardTitle className="text-xl font-bold dark:text-white">
            Tidak ada data yang tersedia
          </CardTitle>
        </CardHeader>
      </Card>
    );
  }

  return (
    <Card className="bg-white dark:bg-slate-900 shadow-lg">
      <CardHeader>
        <CardTitle className="text-xl font-bold dark:text-white">
          Nama Beasiswa
          {selectedYear !== 'all' ? ` Angkatan ${selectedYear}` : ''}
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="h-[300px] sm:h-[300px] md:h-[300px] w-full max-w-5xl mx-auto">
          {typeof window !== 'undefined' && (
            <Chart
              options={chartOptions}
              series={series}
              type="pie"
              height="100%"
              width="100%"
            />
          )}
        </div>
      </CardContent>
    </Card>
  );
}
