'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 AsalDaerahLulusChartProps {
  selectedYear: string;
}

interface ChartData {
  tahun_angkatan: string;
  kabupaten: string;
  jumlah_lulus_tepat_waktu: number;
}

export default function AsalDaerahLulusChart({ selectedYear }: AsalDaerahLulusChartProps) {
  const { theme, systemTheme } = useTheme();
  const [mounted, setMounted] = useState(false);
  const [chartData, setChartData] = useState<ChartData[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [series, setSeries] = useState<ApexAxisChartSeries>([{
    name: 'Jumlah Lulus Tepat Waktu',
    data: []
  }]);

  const [options, setOptions] = useState<ApexOptions>({
    chart: {
      type: 'bar',
      stacked: false,
      toolbar: {
        show: true,
      },
      background: theme === 'dark' ? '#0F172B' : '#fff',
    },
    plotOptions: {
      bar: {
        horizontal: true,
        columnWidth: '55%',
        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: [],
      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: 0
      }
    },
    fill: {
      opacity: 1,
    },
    colors: ['#3B82F6'], // Blue color for bars
    tooltip: {
      theme: theme === 'dark' ? 'dark' : 'light',
      y: {
        formatter: function (val: number) {
          return val + " mahasiswa";
        }
      }
    }
  });

  // Update theme when it changes
  useEffect(() => {
    const currentTheme = theme === 'system' ? systemTheme : theme;
    setOptions(prev => ({
      ...prev,
      chart: {
        ...prev.chart,
        background: currentTheme === 'dark' ? '#0F172B' : '#fff',
      },
      dataLabels: {
        ...prev.dataLabels,
        style: {
          ...prev.dataLabels?.style,
          colors: [currentTheme === 'dark' ? '#fff' : '#000']
        }
      },
      xaxis: {
        ...prev.xaxis,
        title: {
          ...prev.xaxis?.title,
          style: {
            ...prev.xaxis?.title?.style,
            color: currentTheme === 'dark' ? '#fff' : '#000'
          }
        },
        labels: {
          ...prev.xaxis?.labels,
          style: {
            ...prev.xaxis?.labels?.style,
            colors: currentTheme === 'dark' ? '#fff' : '#000'
          }
        }
      },
      yaxis: {
        ...prev.yaxis,
        title: {
          ...(Array.isArray(prev.yaxis) ? prev.yaxis[0]?.title : prev.yaxis?.title),
          style: {
            ...(Array.isArray(prev.yaxis) ? prev.yaxis[0]?.title?.style : prev.yaxis?.title?.style),
            color: currentTheme === 'dark' ? '#fff' : '#000'
          }
        },
        labels: {
          ...(Array.isArray(prev.yaxis) ? prev.yaxis[0]?.labels : prev.yaxis?.labels),
          style: {
            ...(Array.isArray(prev.yaxis) ? prev.yaxis[0]?.labels?.style : prev.yaxis?.labels?.style),
            colors: currentTheme === 'dark' ? '#fff' : '#000'
          }
        }
      },
      tooltip: {
        ...prev.tooltip,
        theme: currentTheme === 'dark' ? 'dark' : 'light'
      }
    }));
  }, [theme, systemTheme]);

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

  useEffect(() => {
    const fetchData = async () => {
      try {
        setIsLoading(true);
        setError(null);
        const response = await fetch(`/api/mahasiswa/asal-daerah-lulus?tahunAngkatan=${selectedYear}`);
        
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }

        const data = await response.json();
        setChartData(data);

        // Process data for chart
        const kabupaten = data.map((item: ChartData) => item.kabupaten);
        const jumlah = data.map((item: ChartData) => item.jumlah_lulus_tepat_waktu);

        setSeries([{
          name: 'Jumlah Lulus Tepat Waktu',
          data: jumlah
        }]);
        setOptions(prev => ({
          ...prev,
          xaxis: {
            ...prev.xaxis,
            categories: kabupaten,
          },
        }));
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred');
        console.error('Error fetching data:', err);
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, [selectedYear]);

  if (!mounted) {
    return null;
  }

  if (isLoading) {
    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 dark:text-red-400">Error: {error}</CardTitle>
        </CardHeader>
      </Card>
    );
  }

  if (chartData.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 Lulus Tepat Waktu
          {selectedYear !== 'all' ? ` Angkatan ${selectedYear}` : ''}
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="h-[600px] w-full">
          <Chart
            options={options}
            series={series}
            type="bar"
            height="100%"
            width="90%"
          />
        </div>
      </CardContent>
    </Card>
  );
} 