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

// Dynamically import ApexCharts to avoid SSR issues
const Chart = dynamic(() => import('react-apexcharts'), { ssr: false });

interface StatusData {
  tahun_angkatan: string;
  status_kuliah: string;
  jumlah: number;
}

interface StatusMahasiswaChartProps {
  height?: string;
  showDetailButton?: boolean;
}

export default function StatusMahasiswaChart({ 
  height = "h-[300px] sm:h-[300px] md:h-[300px]",
  showDetailButton = true 
}: StatusMahasiswaChartProps) {
  const { theme } = useTheme();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [data, setData] = useState<StatusData[]>([]);
  const [series, setSeries] = useState<ApexAxisChartSeries>([]);

  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: false,
        columnWidth: '65%',
      },
    },
    dataLabels: {
      enabled: true,
      formatter: function (val: number) {
        return val.toString();
      },
      style: {
        fontSize: '12px',
        colors: [theme === 'dark' ? '#fff' : '#000']
      }
    },
    stroke: {
      show: true,
      width: 2,
      colors: ['transparent'],
    },
    xaxis: {
      categories: [...new Set(data.map(item => item.tahun_angkatan))].sort(),
      title: {
        text: 'Tahun Angkatan',
        style: {
          fontSize: '14px',
          fontWeight: 'bold',
          color: theme === 'dark' ? '#fff' : '#000'
        }
      },
      labels: {
        style: {
          fontSize: '12px',
          colors: theme === 'dark' ? '#fff' : '#000'
        }
      }
    },
    yaxis: {
      title: {
        text: 'Jumlah Mahasiswa',
        style: {
          fontSize: '14px',
          fontWeight: 'bold',
          color: theme === 'dark' ? '#fff' : '#000'
        }
      },
      labels: {
        style: {
          fontSize: '12px',
          colors: theme === 'dark' ? '#fff' : '#000'
        }
      },
      min:0,
      tickAmount: 5
    },
    fill: {
      opacity: 1,
    },
    legend: {
      position: 'top',
      fontSize: '14px',
      markers: {
        size: 12,
      },
      itemMargin: {
        horizontal: 10,
      },
      labels: {
        colors: theme === 'dark' ? '#fff' : '#000'
      }
    },
    colors: ['#008FFB', '#00E396', '#FEB019', '#EF4444'],
    tooltip: {
      theme: theme === 'dark' ? 'dark' : 'light',
      y: {
        formatter: function (val: number) {
          return val + " mahasiswa";
        }
      }
    }
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        setError(null);
        
        const response = await fetch('/api/mahasiswa/status');
        
        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);

        // Process data to create series
        const tahunAngkatan = [...new Set(result.map(item => item.tahun_angkatan))].sort();
        const statuses = ['Aktif', 'Lulus', 'Cuti', 'Non Aktif'];
        
        const seriesData = statuses.map(status => ({
          name: status,
          data: tahunAngkatan.map(tahun => {
            const item = result.find(d => d.tahun_angkatan === tahun && d.status_kuliah === status);
            return item ? item.jumlah : 0;
          }),
        }));

        setSeries(seriesData);
      } catch (err) {
        console.error('Error in fetchData:', err);
        setError(err instanceof Error ? err.message : 'An error occurred while fetching data');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  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 dark:text-red-400">
            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">
            Status Mahasiswa
          </CardTitle>
          {showDetailButton && (
            <Link href="/detail/status-mahasiswa" 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>
  );
} 