'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 AsalDaerahStatusData {
  kabupaten: string;
  tahun_angkatan?: number;
  status_kuliah: string;
  total_mahasiswa: number;
}

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

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

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        console.log('Fetching data with params:', { selectedYear, selectedStatus });
        
        const response = await fetch(
          `/api/mahasiswa/asal-daerah-status?tahun_angkatan=${selectedYear}&status_kuliah=${selectedStatus}`
        );
        
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }
        
        const result = await response.json();
        console.log('Received data:', result);
        
        // Sort data by kabupaten
        const sortedData = result.sort((a: AsalDaerahStatusData, b: AsalDaerahStatusData) => 
          a.kabupaten.localeCompare(b.kabupaten)
        );
        
        setData(sortedData);
      } catch (err) {
        console.error('Error in fetchData:', err);
        setError(err instanceof Error ? err.message : 'An error occurred');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [selectedYear, selectedStatus]);

  // Log data changes
  useEffect(() => {
    console.log('Current data state:', data);
  }, [data]);

  // Get unique kabupaten
  const kabupaten = [...new Set(data.map(item => item.kabupaten))].sort();
  console.log('Kabupaten:', kabupaten);

  const chartOptions: 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: '12px',
        colors: [theme === 'dark' ? '#fff' : '#000']
      },
      offsetX: 10,
    },
    stroke: {
      show: true,
      width: 2,
      colors: ['transparent'],
    },
    xaxis: {
      categories: kabupaten,
      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: '12px',
          colors: theme === 'dark' ? '#fff' : '#000'
        }
      }
    },
    fill: {
      opacity: 1,
    },
    legend: {
      position: 'top',
      fontSize: '14px',
      markers: {
        size: 12,
      },
      itemMargin: {
        horizontal: 10,
      },
      labels: {
        colors: theme === 'dark' ? '#fff' : '#000'
      }
    },
    colors: ['#008FFB'],
    tooltip: {
      theme: theme === 'dark' ? 'dark' : 'light',
      y: {
        formatter: function (val: number) {
          return val + " mahasiswa";
        }
      }
    }
  };

  // Process data for series
  const processSeriesData = () => {
    const seriesData = kabupaten.map(kab => {
      const item = data.find(d => d.kabupaten === kab);
      return item ? item.total_mahasiswa : 0;
    });

    return [{
      name: 'Jumlah Mahasiswa',
      data: seriesData
    }];
  };

  const series = processSeriesData();

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