import { Election } from '@/lib/db/history';
import { useEffect, useRef } from 'react';

interface VoteShareChartProps {
  selectedElection: Election;
  chartLoaded: boolean;
}

export const VoteShareChart = ({ selectedElection, chartLoaded }: VoteShareChartProps) => {
  const chartRef = useRef<HTMLCanvasElement>(null);
  const chartInstance = useRef<any>(null);

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

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

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

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

    chartInstance.current = new chartOnWindow(ctx, {
      type: 'doughnut',
      data: {
        labels: selectedElection.parties.map((p) => p.nameBn || p.name),
        datasets: [
          {
            data: selectedElection.parties.map((p) => p.votes),
            backgroundColor: selectedElection.parties.map((p) => p.color),
            borderWidth: 0,
            hoverOffset: 10,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: '65%',
        plugins: {
          legend: {
            position: 'bottom',
            labels: {
              font: { family: "'Hind Siliguri', sans-serif", size: 10 },
              padding: 10,
              usePointStyle: true,
              pointStyle: 'circle',
            },
          },
          tooltip: {
            callbacks: {
              label: (ctx: any) => ` ${ctx.label}: ${ctx.raw}%`,
            },
            titleFont: { family: "'Hind Siliguri', sans-serif" },
            bodyFont: { family: "'Hind Siliguri', sans-serif" },
          },
        },
      },
    });

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

  return (
    <div className="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-gray-200 p-3 sm:p-4 md:p-6">
      <h3 className="font-bold text-gray-800 mb-3 sm:mb-4 flex items-center gap-2 text-sm sm:text-base">
        <span className="material-symbols-outlined text-purple-600">pie_chart</span>
        ভোট শতাংশ
      </h3>
      <div className="h-40 sm:h-48">
        <canvas ref={chartRef}></canvas>
      </div>
    </div>
  );
};
