'use client';

import { Chart, registerables } from 'chart.js';
import { useCallback, useEffect, useRef } from 'react';
import { BangladeshElectionData } from '../../dashboard.type';

Chart.register(...registerables);

export const SeatDistributionWidget = ({ data }: { data: BangladeshElectionData }) => {
  const seatChartRef = useRef<Chart | null>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);

  const toBn = (value: number | string) => {
    const bengaliNumerals = ['০', '১', '২', '৩', '৪', '৫', '৬', '৭', '৮', '৯'];
    return value
      .toString()
      .split('')
      .map((digit) => {
        if (digit === '.' || digit === ',') return digit;
        const digitNum = parseInt(digit, 10);
        return Number.isNaN(digitNum) ? digit : bengaliNumerals[digitNum];
      })
      .join('');
  };

  const initSeatDistributionChart = useCallback(() => {
    const ctx = canvasRef.current;
    if (!ctx) return;

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

    const latest = data.elections[0];
    if (!latest) return;

    seatChartRef.current = new Chart(ctx, {
      type: 'doughnut',
      data: {
        labels: latest.parties.map((p) => p.nameBn || p.name),
        datasets: [
          {
            data: latest.parties.map((p) => p.seats),
            backgroundColor: latest.parties.map((p) => p.color),
            borderWidth: 0,
            hoverOffset: 10,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: '60%',
        plugins: {
          legend: {
            position: 'bottom',
            labels: {
              font: { family: "'Hind Siliguri', sans-serif", size: 11 },
              padding: 15,
              usePointStyle: true,
              pointStyle: 'circle',
            },
          },
          tooltip: {
            callbacks: {
              label: (context) => {
                const label = context.label || '';
                const rawValue = context.raw;
                const value = typeof rawValue === 'number' ? rawValue : Number(rawValue || 0);
                const total = (context.dataset.data as number[]).reduce((a, b) => a + b, 0);
                const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : '0.0';
                return ` ${label}: ${toBn(value)} আসন (${percentage}%)`;
              },
            },
            titleFont: { family: "'Hind Siliguri', sans-serif" },
            bodyFont: { family: "'Hind Siliguri', sans-serif" },
          },
        },
      },
    });
  }, [data]);

  useEffect(() => {
    initSeatDistributionChart();
    return () => {
      if (seatChartRef.current) {
        seatChartRef.current.destroy();
      }
    };
  }, [initSeatDistributionChart]);

  return (
    <div className="lg:col-span-1 bg-gray-50 p-6 rounded-3xl">
      <h3 className="text-lg font-bold text-blue-900 mb-4 flex items-center gap-2">
        <span className="material-symbols-outlined text-blue-600">pie_chart</span>
        আসন বিন্যাস
      </h3>
      <div className="relative h-64">
        <canvas ref={canvasRef} id="seatDistributionChart"></canvas>
      </div>
      <p className="text-xs text-gray-500 mt-4 text-center">সংসদ নির্বাচন ২০২৪</p>
    </div>
  );
};
