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

// Import ApexCharts secara dinamis untuk menghindari masalah SSR
const Chart = dynamic(() => import('react-apexcharts'), { ssr: false });

interface AsalDaerahData {
  kabupaten: string;
  jumlah: number;
}

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

export default function AsalDaerahChart({ 
  height = "h-[400px] sm:h-[450px] md:h-[500px] lg:h-[600px]",
  showDetailButton = true 
}: AsalDaerahChartProps = {}) {
  const { theme } = useTheme();
  const [mounted, setMounted] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [data, setData] = useState<AsalDaerahData[]>([]);
  const [series, setSeries] = useState<ApexAxisChartSeries>([{
    name: 'Jumlah Mahasiswa',
    data: []
  }]);
  const [options, setOptions] = useState<ApexOptions>({
    chart: {
      type: 'bar',
      stacked: false,
      toolbar: {
        show: true,
      },
    },
    plotOptions: {
      bar: {
        horizontal: true,
        columnWidth: '85%',
        distributed: false,
        barHeight: '90%',
        dataLabels: {
          position: 'center',
        },
      },
    },
    dataLabels: {
      enabled: true,
      formatter: function (val: number) {
        return val.toString();
      },
      style: {
        fontSize: '12px',
        colors: [theme === 'dark' ? '#fff' : '#000']
      },
    },
    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,
      },
    },
    fill: {
      opacity: 1,
    },
    colors: ['#3B82F6'], // Warna biru untuk bar
    tooltip: {
      theme: theme === 'dark' ? 'dark' : 'light',
      y: {
        formatter: function (val: number) {
          return val + " mahasiswa";
        }
      }
    }
  });

  // Perbarui tema saat berubah
  useEffect(() => {
    setOptions(prev => ({
      ...prev,
      chart: {
        ...prev.chart,
        background: theme === 'dark' ? '#0F172B' : '#fff',
      },
      dataLabels: {
        ...prev.dataLabels,
        style: {
          ...prev.dataLabels?.style,
          colors: [theme === 'dark' ? '#fff' : '#000']
        }
      },
      xaxis: {
        ...prev.xaxis,
        title: {
          ...prev.xaxis?.title,
          style: {
            ...prev.xaxis?.title?.style,
            color: theme === 'dark' ? '#fff' : '#000'
          }
        },
        labels: {
          ...prev.xaxis?.labels,
          style: {
            ...prev.xaxis?.labels?.style,
            colors: theme === '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: theme === '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: theme === 'dark' ? '#fff' : '#000'
          }
        }
      },
      tooltip: {
        ...prev.tooltip,
        theme: theme === 'dark' ? 'dark' : 'light'
      }
    }));
  }, [theme]);

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

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        setError(null);
        
        const response = await fetch('/api/mahasiswa/asal-daerah');
        
        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('Format data tidak valid diterima dari server');
        }
        
        setData(result);

        // Proses data untuk chart
        const kabupaten = result.map(item => item.kabupaten);
        const jumlah = result.map(item => item.jumlah);

        setSeries([{
          name: 'Jumlah Mahasiswa',
          data: jumlah
        }]);
        setOptions(prev => ({
          ...prev,
          xaxis: {
            ...prev.xaxis,
            categories: kabupaten,
          },
        }));
      } catch (err) {
        console.error('Error in fetchData:', err);
        setError(err instanceof Error ? err.message : 'Terjadi kesalahan saat mengambil data');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (!mounted) {
    return null;
  }

  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>
    );
  }

  // Hitung tinggi dinamis berdasarkan jumlah kabupaten
  const calculateHeight = () => {
    const minHeight = 100;
    const barHeight = 15; // Tinggi per bar dalam piksel
    const padding = 100; // Ruang ekstra untuk judul, legenda, dll
    const dynamicHeight = Math.max(minHeight, (data.length * barHeight) + padding);
    return `${dynamicHeight}px`;
  };

  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">
            Asal Kabupaten Mahasiswa
          </CardTitle>
          {showDetailButton && (
            <Link href="/detail/asal-daerah" 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`}
          style={{ height: calculateHeight() }}
        >
          <Chart
            options={options}
            series={series}
            type="bar"
            height="100%"
            width="100%"
          />
        </div>
      </CardContent>
    </Card>
  );
} 