'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 NamaBeasiswaData { tahun_angkatan: number; nama_beasiswa: string; jumlah_nama_beasiswa: number; } interface Props { selectedYear: string; } interface NamaBeasiswaDashChartProps extends Props { height?: string; showDetailButton?: boolean; } export default function NamaBeasiswaDashChart({ selectedYear, height = "h-[300px] sm:h-[300px] md:h-[300px]", showDetailButton = true }: NamaBeasiswaDashChartProps) { const { theme } = useTheme(); const [data, setData] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [chartOptions, setChartOptions] = useState({}); useEffect(() => { const fetchData = async () => { try { setLoading(true); setError(null); const url = `/api/mahasiswa/nama-beasiswa-dashboard?tahunAngkatan=${selectedYear}`; const response = await fetch(url); 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'); } // Sort data by tahun_angkatan const sortedData = result.sort((a: NamaBeasiswaData, b: NamaBeasiswaData) => a.tahun_angkatan - b.tahun_angkatan ); setData(sortedData); // Update chart options dengan categories yang benar const years = [...new Set(sortedData.map(item => item.tahun_angkatan))].sort(); updateChartOptions(years); } catch (err) { console.error('Error in fetchData:', err); setError(err instanceof Error ? err.message : 'An error occurred while fetching data'); } finally { setLoading(false); } }; fetchData(); }, [selectedYear, theme]); // Initialize chart options on mount useEffect(() => { updateChartOptions([]); }, []); // Function to update chart options const updateChartOptions = (years: number[]) => { console.log('Updating chart options with years:', years); setChartOptions({ chart: { type: 'bar', stacked: true, 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: true, barHeight: '70%', }, }, 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: '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 }, colors: ['#3B82F6', '#EC4899', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6', '#06B6D4'], tooltip: { theme: theme === 'dark' ? 'dark' : 'light', shared: true, intersect: false, custom: function({ series, seriesIndex, dataPointIndex, w }: any) { const tahun = w.globals.labels[dataPointIndex]; const isDark = theme === 'dark'; // Hitung total untuk tahun ini let total = 0; series.forEach((seriesData: number[]) => { total += seriesData[dataPointIndex] || 0; }); const beasiswaNames = w.config.series.map((s: any) => s.name); const beasiswaColors = w.config.colors; let tooltipContent = `
Angkatan ${tahun}
`; // Tambahkan setiap jenis beasiswa series.forEach((seriesData: number[], index: number) => { const value = seriesData[dataPointIndex] || 0; tooltipContent += `
${beasiswaNames[index]} ${value}
`; }); // Tambahkan total tooltipContent += `
Total ${total}
`; return tooltipContent; } }, legend: { position: 'top', fontSize: '14px', markers: { size: 12, }, itemMargin: { horizontal: 10, }, labels: { colors: theme === 'dark' ? '#fff' : '#000' } }, grid: { borderColor: theme === 'dark' ? '#374151' : '#E5E7EB', strokeDashArray: 4, padding: { top: 20, right: 0, bottom: 0, left: 0 } } }); }; // Process data for series const processSeriesData = () => { if (!data.length) return []; const years = [...new Set(data.map(item => item.tahun_angkatan))].sort(); const beasiswaTypes = [...new Set(data.map(item => item.nama_beasiswa))].sort(); return beasiswaTypes.map(beasiswa => ({ name: beasiswa, data: years.map(year => { const item = data.find(d => d.tahun_angkatan === year && d.nama_beasiswa === beasiswa); return item ? item.jumlah_nama_beasiswa : 0; }) })); }; const series = processSeriesData(); if (loading) { return ( Loading... ); } if (error) { return ( Error: {error} ); } if (data.length === 0) { return ( Tidak ada data yang tersedia ); } return (
Nama Beasiswa Mahasiswa {selectedYear !== 'all' ? ` Angkatan ${selectedYear}` : ''} {showDetailButton && ( )}
{typeof window !== 'undefined' && series.length > 0 && Object.keys(chartOptions).length > 0 && ( )}
); }