import { HistoricalPerformance } from '@/lib/db/history';
import { toBn } from '@/lib/utils';
import { useEffect, useRef } from 'react';

interface HistoricalDivisionChartProps {
  historicalPerformance: HistoricalPerformance;
  chartLoaded: boolean;
}

export const HistoricalDivisionChart = ({
  historicalPerformance,
  chartLoaded,
}: HistoricalDivisionChartProps) => {
  const historicalChartRef = useRef<HTMLCanvasElement>(null);
  const historicalChartInstance = useRef<any>(null);

  useEffect(() => {
    const chartOnWindow =
      typeof window !== 'undefined' ? (window as Window & { Chart?: any }).Chart : undefined;

    if (!chartLoaded || !historicalChartRef.current || !chartOnWindow) return;

    if (historicalChartInstance.current) {
      historicalChartInstance.current.destroy();
    }

    const ctx = historicalChartRef.current.getContext('2d');
    if (!ctx) return;

    historicalChartInstance.current = new chartOnWindow(ctx, {
      type: 'line',
      data: {
        labels: historicalPerformance.years.map((y) => toBn(y)),
        datasets: [
          {
            label: 'আওয়ামী লীগ',
            data: historicalPerformance.awamiLeague.seats,
            borderColor: '#006A4E',
            backgroundColor: 'rgba(0, 106, 78, 0.1)',
            borderWidth: 3,
            tension: 0.3,
            fill: true,
          },
          {
            label: 'বিএনপি',
            data: historicalPerformance.bnp.seats,
            borderColor: '#ED1B24',
            backgroundColor: 'rgba(237, 27, 36, 0.1)',
            borderWidth: 3,
            tension: 0.3,
            fill: true,
          },
          {
            label: 'জাতীয় পার্টি',
            data: historicalPerformance.jatiyaParty.seats,
            borderColor: '#9333EA',
            backgroundColor: 'rgba(147, 51, 234, 0.1)',
            borderWidth: 3,
            tension: 0.3,
            fill: true,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'top',
            labels: {
              font: { family: "'Hind Siliguri', sans-serif", size: 14 },
              usePointStyle: true,
            },
          },
          tooltip: {
            mode: 'index',
            intersect: false,
            callbacks: {
              label: (ctx: any) => ` ${ctx.dataset.label}: ${toBn(ctx.raw)} আসন`,
            },
            titleFont: { family: "'Hind Siliguri', sans-serif" },
            bodyFont: { family: "'Hind Siliguri', sans-serif" },
          },
        },
        scales: {
          y: {
            beginAtZero: true,
            title: {
              display: true,
              text: 'আসন সংখ্যা',
              font: { family: "'Hind Siliguri', sans-serif", size: 14 },
            },
            ticks: {
              font: { family: "'Hind Siliguri', sans-serif" },
              callback: (value: any) => toBn(value),
            },
          },
          x: {
            grid: { display: false },
            ticks: {
              font: { family: "'Hind Siliguri', sans-serif" },
            },
          },
        },
      },
    });

    return () => {
      if (historicalChartInstance.current) {
        historicalChartInstance.current.destroy();
      }
    };
  }, [chartLoaded, historicalPerformance]);

  return (
    <div className="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-gray-200 overflow-hidden mb-6 sm:mb-8">
      <div className="bg-linear-to-r from-indigo-600 to-indigo-800 text-white px-3 sm:px-4 md:px-6 py-2.5 sm:py-3 md:py-4">
        <h3 className="text-base sm:text-lg font-bold flex items-center gap-2">
          <span className="material-symbols-outlined">history</span>
          ঐতিহাসিক নির্বাচনী ফলাফল (১৯৯১ - ২০২৪)
        </h3>
      </div>
      <div className="p-4 sm:p-6 h-64 sm:h-80 md:h-96">
        <canvas ref={historicalChartRef}></canvas>
      </div>
    </div>
  );
};
