'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";

// Dynamically import ApexCharts to avoid SSR issues
const Chart = dynamic(() => import('react-apexcharts'), { ssr: false });

interface LulusTepatWaktuData {
  tahun_angkatan: number;
  jk: string;
  jumlah_lulus_tepat_waktu: number;
}

interface Props {
  selectedYear: string;
}

export default function LulusTepatWaktuPieChart({ selectedYear }: Props) {
  const { theme } = useTheme();
  const [data, setData] = useState<LulusTepatWaktuData[]>([]);
  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/lulus-tepat-waktu?tahun_angkatan=${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();
        setData(result);
      } 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]);

  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: ['Laki-laki', 'Perempuan'],
    colors: ['#3B82F6', '#EC4899'],
    legend: {
      position: 'bottom',
      fontSize: '14px',
      markers: {
        size: 12,
        strokeWidth: 0
      },
      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'
      },
      offsetY: 0,
      dropShadow: {
        enabled: false
      }
    },
    tooltip: {
      theme: theme === 'dark' ? 'dark' : 'light',
      y: {
        formatter: function (val: number) {
          return val + " mahasiswa"
        }
      }
    }
  };

  const processSeriesData = () => {
    const maleData = data.find(item => item.jk === 'Pria')?.jumlah_lulus_tepat_waktu || 0;
    const femaleData = data.find(item => item.jk === 'Wanita')?.jumlah_lulus_tepat_waktu || 0;
    return [maleData, femaleData];
  };

  const series = processSeriesData();
  const totalMahasiswa = data.reduce((sum, item) => sum + item.jumlah_lulus_tepat_waktu, 0);

  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">
          Mahasiswa Lulus Tepat Waktu
          {selectedYear !== 'all' ? ` Angkatan ${selectedYear}` : ''}
        </CardTitle>
        <div className="text-lg font-semibold text-gray-600 dark:text-gray-300">
          Total Mahasiswa: {totalMahasiswa}
        </div>
      </CardHeader>
      <CardContent>
        <div className="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>
  );
} 