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

export const WealthChart = ({ 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: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: { display: false },
              tooltip: {
                callbacks: {
                  label: (ctx: any) =>
                    ` সম্পদ: ${toBn(makeAmountShortar(ctx.raw).value)} ${makeAmountShortar(ctx.raw).type}`,
                },
                bodyFont: { family: "'Hind Siliguri', sans-serif", size: 11 },
              },
            },
            scales: {
              y: {
                beginAtZero: true,
                grid: { color: '#eff6ff' },
                ticks: {
                  font: { family: "'Hind Siliguri', sans-serif", size: 9 },
                  callback: (value: any) => toBn(value),
                },
              },
              x: {
                grid: { display: false },
                ticks: { font: { family: "'Hind Siliguri', sans-serif", size: 9 } },
              },
            },
          },
        });
      }
    }

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

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

    const labels = selectedData.map((c) => c.name_bn);

    chartInstance.current.data.labels = labels;
    chartInstance.current.data.datasets = [
      {
        label: 'সম্পদ (কোটি টাকা)',
        data: selectedData.map((c) => c.tax_return_info.total_visible_income),
        backgroundColor: selectedData.map((c, i) => (i === 0 ? '#2563eb' : '#94a3b8')),
        borderRadius: 4,
        barThickness: 20,
        maxBarThickness: 25,
      },
    ];
    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-yellow-500 text-lg">attach_money</span>
        সম্পদ বিবরণী (কোটি টাকায়)
      </h4>
      <div className="chart-container">
        <canvas ref={chartRef}></canvas>
      </div>
      <p className="text-xs text-gray-400 mt-4 text-center">* হলফনামা অনুযায়ী তথ্য প্রদর্শিত</p>
    </div>
  );
};
