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

const Chart = dynamic(() => import('react-apexcharts'), { ssr: false });

interface Props {
  tahunAngkatan: string;
}

export default function IPKJenisKelaminChart({ tahunAngkatan }: Props) {
  const { theme, systemTheme } = useTheme();
  const [mounted, setMounted] = useState(false);
  const [series, setSeries] = useState<any[]>([]);
  const [categories, setCategories] = useState<string[]>([]);
  
  const [options, setOptions] = useState<ApexOptions>({
    chart: {
      type: 'bar',
      toolbar: {
        show: true,
        tools: {
          download: true,
          selection: true,
          zoom: true,
          zoomin: true,
          zoomout: true,
          pan: true,
          reset: true,
          customIcons: []
        },
        export: {
          csv: {
            filename: `ipk-jenis-kelamin-angkatan`,
            columnDelimiter: ',',
            headerCategory: 'Jenis Kelamin',
            headerValue: 'Rata-rata IPK'
          }
        },
      },
      background: theme === 'dark' || systemTheme === 'dark' ? '#0F172B' : '#fff',
    },
    colors: ['#3B82F6', '#EC4899'],
    plotOptions: {
      bar: {
        horizontal: false,
        columnWidth: '30%',
        borderRadius: 2,
        distributed: true
      },
    },
    states: {
      hover: {
        filter: {
          type: 'none'
        }
      },
      active: {
        filter: {
          type: 'none'
        }
      }
    },
    fill: {
      opacity: 1
    },
    dataLabels: {
      enabled: true,
      formatter: function (val: number) {
        return val.toFixed(2);
      },
      offsetY: -20,
      style: {
        fontSize: '14px',
        fontWeight: 'bold',
        colors: [theme === 'dark' || systemTheme === 'dark' ? '#fff' : '#000']
      }
    },
    xaxis: {
      categories: [],
      title: {
        text: 'Jenis Kelamin',
        style: {
          fontSize: '14px',
          fontWeight: 'bold',
          color: theme === 'dark' || systemTheme === 'dark' ? '#fff' : '#000'
        }
      }
    },
    yaxis: {
      min: 0,
      max: 4.0,
      tickAmount: 4,
      title: {
        text: 'Rata-rata IPK',
        style: {
          fontSize: '14px',
          fontWeight: 'bold',
          color: theme === 'dark' || systemTheme === 'dark' ? '#fff' : '#000'
        }
      }
    },
    tooltip: {
      theme: theme === 'dark' || systemTheme === 'dark' ? 'dark' : 'light',
      y: {
        formatter: function (val: number) {
          return val.toFixed(2) + " IPK";
        }
      },
    },
    legend: {
      show: false
    }
  });

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

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

  useEffect(() => {
    const fetchData = async () => {
      if (!tahunAngkatan || tahunAngkatan === 'all') {
        console.log('Tahun angkatan tidak tersedia atau "all"');
        return;
      }

      console.log('Fetching data for tahun angkatan:', tahunAngkatan);
      const url = `/api/mahasiswa/ipk-jenis-kelamin?tahun_angkatan=${tahunAngkatan}`;
      console.log('API URL:', url);
      
      const response = await fetch(url);
      
      if (!response.ok) {
        console.error('Error response:', response.status, response.statusText);
        return;
      }
      
      const data = await response.json();
      console.log('Data received from API:', data);

      if (!data || data.length === 0) {
        console.log('No data received from API');
        return;
      }

      // Process data for chart
      const labels = data.map((item: any) => {
        console.log('Processing item:', item);
        return item.jk === 'Pria' ? 'Laki-laki' : 'Perempuan';
      });
      
      const values = data.map((item: any) => {
        const ipk = parseFloat(item.rata_rata_ipk);
        console.log(`IPK for ${item.jk}:`, ipk);
        return ipk;
      });

      console.log('Processed labels:', labels);
      console.log('Processed values:', values);

      if (values.length === 0) {
        console.log('No values to display');
        return;
      }

      setCategories(labels);
      // Untuk bar chart, kita memerlukan array dari objects
      setSeries([{
        name: 'Rata-rata IPK',
        data: values
      }]);
      
      setOptions(prev => ({
        ...prev,
        xaxis: {
          ...prev.xaxis,
          categories: labels
        },
        chart: {
          ...prev.chart,
          toolbar: {
            ...prev.chart?.toolbar,
            export: {
              ...prev.chart?.toolbar?.export,
              csv: {
                ...prev.chart?.toolbar?.export?.csv,
                filename: `ipk-jenis-kelamin-angkatan-${tahunAngkatan}`
              }
            }
          }
        }
      }));
    };

    if (mounted) {
      fetchData();
    }
  }, [tahunAngkatan, mounted]);

  if (!mounted) {
    return null;
  }

  return (
    <Card className="bg-white dark:bg-slate-900 shadow-lg">
      <CardHeader>
        <CardTitle className="text-xl font-bold dark:text-white">
          Rata-rata IPK Berdasarkan Jenis Kelamin Angkatan {tahunAngkatan}
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="h-[400px] w-full">
          {series.length > 0 && series[0].data?.length > 0 ? (
            <Chart
              options={{
                ...options,
                xaxis: {
                  ...options.xaxis,
                  categories: categories
                }
              }}
              series={series}
              type="bar"
              height="100%"
              width="90%"
            />
          ) : (
            <div className="flex items-center justify-center h-full">
              <p className="text-gray-500 dark:text-gray-400">Tidak ada data</p>
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  );
} 