'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 AsalDaerahPrestasiData {
  tahun_angkatan: number;
  kabupaten: string;
  asal_daerah_mahasiswa_prestasi: number;
}

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

export default function AsalDaerahPrestasiChart({ selectedYear, selectedJenisPrestasi }: Props) {
  const { theme } = useTheme();
  const [mounted, setMounted] = useState(false);
  const [data, setData] = useState<AsalDaerahPrestasiData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        setError(null);
        
        const url = `/api/mahasiswa/asal-daerah-prestasi?tahunAngkatan=${selectedYear}&jenisPrestasi=${selectedJenisPrestasi}`;
        
        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();
  }, [selectedYear, selectedJenisPrestasi]);

  const chartOptions: ApexOptions = {
    chart: {
      type: 'bar',
      stacked: false,
      toolbar: {
        show: true,
        tools: {
          download: true,
          selection: true,
          zoom: true,
          zoomin: true,
          zoomout: true,
          pan: true,
          reset: true
        }
      },
      background: theme === 'dark' ? '#0F172B' : '#fff',
    },
    plotOptions: {
      bar: {
        horizontal: true,
        columnWidth: '85%',
        distributed: false,
        barHeight: '90%',
        dataLabels: {
          position: 'top'
        }
      },
    },
    dataLabels: {
      enabled: true,
      formatter: function (val: number) {
        return val.toString();
      },
      style: {
        fontSize: '14px',
        colors: [theme === 'dark' ? '#fff' : '#000']
      },
      offsetX: 10,
    },
    stroke: {
      show: true,
      width: 1,
      colors: [theme === 'dark' ? '#374151' : '#E5E7EB'],
    },
    xaxis: {
      categories: [...new Set(data.map(item => item.kabupaten))].sort(),
      title: {
        text: 'Jumlah Mahasiswa',
        style: {
          fontSize: '14px',
          fontWeight: 'bold',
          color: theme === 'dark' ? '#fff' : '#000'
        }
      },
      labels: {
        style: {
          fontSize: '12px',
          colors: theme === 'dark' ? '#fff' : '#000'
        }
      }
    },
    yaxis: {
      title: {
        text: 'Kabupaten',
        style: {
          fontSize: '14px',
          fontWeight: 'bold',
          color: theme === 'dark' ? '#fff' : '#000'
        }
      },
      labels: {
        style: {
          fontSize: '14px',
          colors: theme === 'dark' ? '#fff' : '#000'
        },
        maxWidth: 200,
      },
    },
    grid: {
      padding: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 10
      }
    },
    fill: {
      opacity: 1,
    },
    colors: ['#3B82F6'],
    tooltip: {
      theme: theme === 'dark' ? 'dark' : 'light',
      y: {
        formatter: function (val: number) {
          return val + " mahasiswa";
        }
      }
    }
  };

  const series = [{
    name: 'Jumlah Mahasiswa',
    data: [...new Set(data.map(item => item.kabupaten))].sort().map(kabupaten => {
      const item = data.find(d => d.kabupaten === kabupaten);
      return item ? item.asal_daerah_mahasiswa_prestasi : 0;
    })
  }];

  if (!mounted) {
    return null;
  }

  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">
          Asal Daerah Mahasiswa Prestasi {selectedJenisPrestasi}
          {selectedYear !== 'all' ? ` Angkatan ${selectedYear}` : ''}
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="h-[300px] sm:h-[300px] md:h-[300px] w-full max-w-5xl mx-auto">
          <Chart
            options={chartOptions}
            series={series}
            type="bar"
            height="100%"
            width="100%"
          />
        </div>
      </CardContent>
    </Card>
  );
} 