'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 ProvinsiMahasiswaData {
  provinsi: string;
  jumlah_mahasiswa: number;
}

export default function ProvinsiMahasiswaPieChart() {
  const { theme } = useTheme();
  const [data, setData] = useState<ProvinsiMahasiswaData[]>([]);
  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/provinsi-mahasiswa`;
        
        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');
        }
        
        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();
  }, []);

  const chartOptions: ApexOptions = {
    chart: {
      type: 'pie',
      background: theme === 'dark' ? '#0F172B' : '#fff',
    },
    labels: data.map(item => item.provinsi),
    colors: ['#3B82F6', '#10B981'],
    legend: {
      position: 'bottom',
      fontSize: '14px',
      markers: {
        size: 12,
      },
      itemMargin: {
        horizontal: 10,
        vertical: 5,
      },
      labels: {
        colors: theme === 'dark' ? '#fff' : '#000'
      }
    },
    dataLabels: {
      enabled: true,
      formatter: function (val: number) {
        return `${val.toFixed(0)}%`;
      },
      style: {
        fontSize: '14px',
        fontWeight: 'bold',
      },
      offsetY: -10,
      dropShadow: {
        enabled: true,
        opacity: 0.3,
        blur: 3,
        color: '#000',
      }
    },
    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',
        },
      },
    },
  };

  const series = data.map(item => item.jumlah_mahasiswa);

  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>
    );
  }

  const totalMahasiswa = data.reduce((sum, item) => sum + item.jumlah_mahasiswa, 0);

  return (
    <Card className="bg-white dark:bg-slate-900 shadow-lg">
      <CardHeader>
        <CardTitle className="text-xl font-bold dark:text-white">
          Asal Provinsi Mahasiswa
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="h-[300px] w-full max-w-5xl mx-auto">
          {typeof window !== 'undefined' && series.length > 0 && (
            <Chart
              options={chartOptions}
              series={series}
              type="pie"
              height="100%"
              width="100%"
            />
          )}
        </div>
      </CardContent>
    </Card>
  );
}
