import { toBn } from '@/lib/utils';
import Chart from 'chart.js/auto';
import { useEffect, useRef } from 'react';
import type { TurnoutTrendChartProps } from '../../seat.type';

export function TurnoutTrendChart({}: TurnoutTrendChartProps) {
  const turnoutTrendChartRef = useRef<HTMLCanvasElement>(null);
  const turnoutChartInstance = useRef<Chart | null>(null);

  useEffect(() => {
    if (turnoutChartInstance.current) {
      turnoutChartInstance.current.destroy();
    }

    if (turnoutTrendChartRef.current) {
      turnoutChartInstance.current = new Chart(turnoutTrendChartRef.current, {
        type: 'line',
        data: {
          labels: ['১৯৯৬', '২০০১', '২০০৮', '২০১৪', '২০১৮'],
          datasets: [
            {
              label: 'ভোট প্রদানের হার (%)',
              data: [78, 75, 87, 40, 80],
              borderColor: '#6366f1',
              backgroundColor: 'rgba(99, 102, 241, 0.1)',
              borderWidth: 2,
              tension: 0.4,
              fill: true,
              pointBackgroundColor: '#fff',
              pointBorderColor: '#6366f1',
              pointRadius: 4,
            },
          ],
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: { display: false },
            tooltip: {
              callbacks: { label: (c) => toBn(c.raw as number) + '%' },
            },
          },
          scales: {
            y: {
              beginAtZero: true,
              max: 100,
              grid: { color: '#f1f5f9' },
              ticks: { callback: (v) => toBn(v as number) },
            },
            x: {
              grid: { display: false },
            },
          },
        },
      });
    }

    return () => {
      if (turnoutChartInstance.current) {
        turnoutChartInstance.current.destroy();
      }
    };
  }, []);

  return (
    <div className="bg-white rounded-2xl shadow-sm border border-slate-200 p-6">
      <h3 className="text-sm font-bold text-slate-800 mb-4 uppercase tracking-wider">
        ভোট প্রদানের হার (ইতিহাস)
      </h3>
      <div className="relative h-48">
        <canvas ref={turnoutTrendChartRef}></canvas>
      </div>
      <p className="text-xs text-slate-400 text-center mt-2">বিগত ৫টি নির্বাচনের উপাত্ত</p>
    </div>
  );
}
