import Chart from '@/lib/chartjs-config';
import { toBn } from '@/lib/utils';
import { Candidate } from '@/type/candidate.type';
import { useEffect, useRef } from 'react';

export const RadarChart = ({ selectedData }: { selectedData: Candidate[] }) => {
  const chartRef = useRef<HTMLCanvasElement>(null);
  const chartInstance = useRef<any>(null);

  useEffect(() => {
    if (chartRef.current && !chartInstance.current) {
      const ctx = chartRef.current.getContext('2d');
      if (ctx) {
        chartInstance.current = new Chart(ctx, {
          type: 'bar',
          data: {
            labels: ['জনপ্রিয়তা', 'সংসদীয় উপস্থিতি', 'ইশতেহার মান', 'জনসেবা'],
            datasets: [],
          },
          options: {
            indexAxis: 'y',
            responsive: true,
            maintainAspectRatio: false,
            scales: {
              x: {
                beginAtZero: true,
                max: 10,
                grid: { color: '#eff6ff' },
                ticks: {
                  stepSize: 2,
                  callback: (value: any) => toBn(value),
                },
              },
              y: {
                grid: { display: false },
                ticks: {
                  font: { family: "'Hind Siliguri', sans-serif", size: 13, weight: 'bold' },
                },
              },
            },
            plugins: {
              legend: {
                position: 'top',
                labels: {
                  font: { family: "'Hind Siliguri', sans-serif", size: 10 },
                  boxWidth: 8,
                  padding: 4,
                },
              },
              tooltip: {
                backgroundColor: 'rgba(6, 78, 59, 0.9)',
                titleFont: { family: "'Hind Siliguri', sans-serif" },
                bodyFont: { family: "'Hind Siliguri', sans-serif" },
                callbacks: { label: (ctx: any) => ` ${ctx.dataset.label}: ${toBn(ctx.raw)}` },
              },
            },
          },
        });
      }
    }

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

  useEffect(() => {
    if (selectedData.length === 0 || !chartInstance.current) return;

    const colors = [
      { bg: '#2563eb', border: '#1e40af' },
      { bg: '#fbbf24', border: '#b45309' },
      { bg: '#8b5cf6', border: '#6d28d9' },
      { bg: '#10b981', border: '#047857' },
      { bg: '#ef4444', border: '#b91c1c' },
    ];

    chartInstance.current.data.datasets = selectedData.map((c, i) => {
      const colorSet = colors[i % colors.length];
      return {
        label: c.name_bn,
        data: [
          c?.popularity / 10,
          c?.attendance / 10,
          c?.manifesto_rating,
          Math.min(c?.public_service_years / 2, 10),
        ],
        backgroundColor: colorSet.bg,
        borderRadius: 4,
        barThickness: 10,
        maxBarThickness: 12,
      };
    });
    chartInstance.current.update();
  }, [selectedData]);

  return (
    <div className="chart-card bg-white p-3 md:p-3.5 rounded-3xl shadow-sm border border-blue-100">
      <h4 className="font-bold text-blue-950 mb-2 md:mb-6 flex items-center gap-1.5">
        <span className="material-symbols-outlined text-purple-500 text-lg">bar_chart_4_bars</span>
        গুণগত মান বিশ্লেষণ
      </h4>
      <div className="chart-container">
        <canvas ref={chartRef}></canvas>
      </div>
      <p className="text-xs text-gray-400 mt-4 text-center">* ১০-এর স্কেলে রেটিং</p>
    </div>
  );
};
