'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";
import { Button } from "@/components/ui/button";
import { ExternalLink } from "lucide-react";
import Link from "next/link";

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

interface KelompokKeahlianStatusData {
  tahun_angkatan: number;
  nama_kelompok: string;
  jumlah_mahasiswa: number;
}

interface Props {
  selectedYear: string;
}

interface KelompokKeahlianStatusChartProps extends Props {
  height?: string;
  showDetailButton?: boolean;
}

export default function KelompokKeahlianStatusChart({ 
  selectedYear, 
  height = "h-[300px] sm:h-[300px] md:h-[300px]",
  showDetailButton = true 
}: KelompokKeahlianStatusChartProps) {
  const { theme } = useTheme();
  const [data, setData] = useState<KelompokKeahlianStatusData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await fetch(
          `/api/mahasiswa/kk-dashboard?tahun_angkatan=${selectedYear}`
        );
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }
        const result = await response.json();
        const sortedData = result.sort((a: KelompokKeahlianStatusData, b: KelompokKeahlianStatusData) => 
          a.nama_kelompok.localeCompare(b.nama_kelompok)
        );
        setData(sortedData);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred');
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [selectedYear]);

  // Get unique tahun_angkatan (series)
  const years = [...new Set(data.map(item => item.tahun_angkatan))].sort((a, b) => Number(a) - Number(b));
  // Get unique kelompok keahlian (x axis)
  const kelompokList = [...new Set(data.map(item => item.nama_kelompok))];

  // Process data for series
  const processSeriesData = () => {
    return kelompokList.map(kelompok => {
      const seriesData = years.map(tahun => {
        const found = data.find(item => item.tahun_angkatan === tahun && item.nama_kelompok === kelompok);
        return found ? found.jumlah_mahasiswa : 0;
      });
      return {
        name: kelompok,
        data: seriesData
      };
    });
  };

  const series = processSeriesData();

  const chartOptions: ApexOptions = {
    chart: {
      type: 'bar',
      stacked: true,
      toolbar: {
        show: true,
      },
      background: theme === 'dark' ? '#0F172B' : '#fff',
    },
    plotOptions: {
      bar: {
        horizontal: true,
        columnWidth: '55%',
      },
    },
    dataLabels: {
      enabled: true,
      formatter: function (val: number, opts: any) {
        const seriesIndex = opts.seriesIndex;
        const dataPointIndex = opts.dataPointIndex;
        
        // Hitung total untuk tahun angkatan ini
        const allSeries = opts.w.config.series;
        let totalForYear = 0;
        allSeries.forEach((series: any) => {
          totalForYear += series.data[dataPointIndex] || 0;
        });
        
        if (totalForYear === 0 || val === 0) return '0%';
        
        const percentage = ((val / totalForYear) * 100).toFixed(0);
        return percentage + '%';
      },
      style: {
        fontSize: '12px',
        colors: [theme === 'dark' ? '#fff' : '#000']
      }
    },
    stroke: {
      show: true,
      width: 2,
      colors: ['transparent'],
    },
    xaxis: {
        categories: years.map(y => y.toString()),
        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: 'Tahun Angkatan',
        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', '#00E396', '#FEB019', '#FF4560', '#775DD0', '#8B5CF6', '#EC4899', '#06B6D4', '#F97316'],
    tooltip: {
      theme: theme === 'dark' ? 'dark' : 'light',
      shared: true,
      intersect: false,
      custom: function({ series, seriesIndex, dataPointIndex, w }: any) {
        const tahun = w.globals.labels[dataPointIndex];
        
        // Hitung total untuk tahun ini
        let total = 0;
        series.forEach((seriesData: number[]) => {
          total += seriesData[dataPointIndex] || 0;
        });
        
        const isDark = theme === 'dark';
        
        let tooltipContent = `
          <div style="
            padding: 12px 16px; 
            background: ${isDark ? 'rgba(30, 41, 59, 0.95)' : 'rgba(255, 255, 255, 0.95)'}; 
            backdrop-filter: blur(10px);
            border: none; 
            border-radius: 12px; 
            box-shadow: 0 8px 32px ${isDark ? 'rgba(0, 0, 0, 0.3)' : 'rgba(0, 0, 0, 0.1)'};
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            min-width: 200px;
          ">
            <div style="
              font-size: 13px; 
              font-weight: 600; 
              color: ${isDark ? '#f1f5f9' : '#1f2937'}; 
              margin-bottom: 8px;
              text-align: center;
            ">Angkatan ${tahun}</div>
        `;
        
        // Tampilkan setiap kelompok keahlian
        w.config.series.forEach((seriesItem: any, index: number) => {
          const value = series[index][dataPointIndex] || 0;
          const color = w.config.colors[index];
          
          tooltipContent += `
            <div style="display: flex; align-items: center; margin-bottom: 4px;">
              <div style="width: 8px; height: 8px; background: ${color}; border-radius: 50%; margin-right: 8px;"></div>
              <span style="font-size: 12px; color: ${isDark ? '#cbd5e1' : '#374151'}; flex: 1;">${seriesItem.name}</span>
              <span style="font-size: 12px; font-weight: 600; color: ${isDark ? '#f1f5f9' : '#1f2937'}; margin-left: auto;">${value}</span>
            </div>
          `;
        });
        
        // Tampilkan total
        tooltipContent += `
          <div style="
            border-top: 1px solid ${isDark ? '#475569' : '#e5e7eb'}; 
            margin-top: 8px; 
            padding-top: 8px;
            display: flex; 
            align-items: center;
          ">
            <div style="width: 8px; height: 8px; background: #10B981; border-radius: 50%; margin-right: 8px;"></div>
            <span style="font-size: 12px; font-weight: 600; color: ${isDark ? '#f1f5f9' : '#1f2937'};">Total</span>
            <span style="font-size: 13px; font-weight: 700; color: #10B981; margin-left: auto;">${total}</span>
          </div>
        </div>
        `;
        
        return tooltipContent;
      }
    }
  };

  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>
        <div className="flex justify-between items-center">
          <CardTitle className="text-xl font-bold dark:text-white">
            Kelompok Keahlian Mahasiswa
            {selectedYear !== 'all' ? ` Angkatan ${selectedYear}` : ''}
          </CardTitle>
          {showDetailButton && (
            <Link href="/detail/kelompok-keahlian" target="_blank">
              <Button variant="outline" size="sm" className="flex items-center gap-1 dark:text-white">
                <ExternalLink className="size-3" />
                Detail
              </Button>
            </Link>
          )}
        </div>
      </CardHeader>
      <CardContent>
        <div className={`${height} w-full max-w-5xl mx-auto`}>
          {typeof window !== 'undefined' && (
            <Chart
              options={chartOptions}
              series={series}
              type="bar"
              height="100%"
              width="100%"
            />
          )}
        </div>
      </CardContent>
    </Card>
  );
}