'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 KelompokKeahlianStatusData {
  tahun_angkatan: number;
  status_kuliah: string;
  nama_kelompok: string;
  jumlah_mahasiswa: number;
}

interface Props {
  selectedYear: string;
  selectedStatus: string;
}

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

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await fetch(
          `/api/mahasiswa/kelompok-keahlian-status?tahun_angkatan=${selectedYear}&status_kuliah=${selectedStatus}`
        );
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }
        const result = await response.json();
        // Sort data by nama_kelompok
        const sortedData = result.sort((a: KelompokKeahlianStatusData, b: KelompokKeahlianStatusData) => 
          a.nama_kelompok.localeCompare(b.nama_kelompok)
        );
        setData(sortedData);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred');
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [selectedYear, selectedStatus]);

  // Pie chart: label = nama_kelompok, value = jumlah_mahasiswa
  const labels = data.map(item => item.nama_kelompok);
  const series = data.map(item => item.jumlah_mahasiswa);

  const chartOptions: ApexOptions = {
    chart: {
      type: 'pie',
      background: theme === 'dark' ? '#0F172B' : '#fff',
    },
    labels,
    legend: {
      position: 'bottom',
      fontSize: '14px',
      markers: {
        size: 12,
      },
      itemMargin: {
        horizontal: 10,
      },
      labels: {
        colors: theme === 'dark' ? '#fff' : '#000'
      }
    },
    dataLabels: {
      enabled: true,
      formatter: function (val: number) {
        return `${val.toFixed(0)}%`;
      },
      style: {
        fontSize: '14px',
        fontFamily: 'Inter, sans-serif',
        fontWeight: '500'
      },
    },
    tooltip: {
      theme: theme === 'dark' ? 'dark' : 'light',
      y: {
        formatter: function (val: number) {
          return val + ' mahasiswa';
        }
      }
    },
    colors: ['#008FFB', '#00E396', '#FEB019', '#FF4560', '#775DD0', '#8B5CF6', '#EC4899', '#06B6D4', '#F97316'],
  };

  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">
          Kelompok Keahlian Mahasiswa {selectedStatus}
          {selectedYear !== 'all' ? ` Angkatan ${selectedYear}` : ''}
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="h-[300px] w-full max-w-3xl mx-auto">
          {typeof window !== 'undefined' && (
            <Chart
              options={chartOptions}
              series={series}
              type="pie"
              height="100%"
              width="100%"
            />
          )}
        </div>
      </CardContent>
    </Card>
  );
} 