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 FamilyWealthChart = ({ 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,
            scales: {
              x: {
                stacked: true,
                grid: { display: false },
                ticks: { font: { family: "'Hind Siliguri', sans-serif", size: 9 } },
              },
              y: {
                stacked: true,
                grid: { color: '#eff6ff' },
                ticks: {
                  font: { family: "'Hind Siliguri', sans-serif", size: 9 },
                  callback: (value: any) => toBn(value),
                },
              },
            },
            plugins: {
              legend: {
                position: 'bottom',
                labels: {
                  font: { family: "'Hind Siliguri', sans-serif", size: 10 },
                  boxWidth: 8,
                  usePointStyle: true,
                },
              },
              tooltip: {
                callbacks: {
                  label: (ctx: any) =>
                    ` ${ctx.dataset.label}: ${toBn(makeAmountShortar(ctx.raw).value)} ${makeAmountShortar(ctx.raw).type}`,
                },
                bodyFont: { family: "'Hind Siliguri', sans-serif", size: 11 },
              },
            },
          },
        });
      }
    }

    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);
    const parse = (v: string | null | undefined) => (v ? parseFloat(v) : 0);

    // Candidate Wealth
    const candidateWealth = selectedData.map((c) => parse(c.tax_return_info?.total_visible_income)); // Using income as proxy or net wealth better? Using income for now as per other charts

    // Family Wealth (Sum of family member incomes/assets)
    // Assuming family_member_annual_incomes is populated
    const familyWealth = selectedData.map((c) => {
      let total = 0;
      c.family_member_annual_incomes?.forEach((fm) => {
        total +=
          parse(fm.agricultural_income) +
          parse(fm.business_income) +
          parse(fm.salary_income) +
          parse(fm.other_income);
      });
      return total;
    });

    chartInstance.current.data.labels = labels;
    chartInstance.current.data.datasets = [
      {
        label: 'নিজস্ব সম্পদ',
        data: candidateWealth,
        backgroundColor: '#3b82f6',
        borderRadius: 4,
        barThickness: 20,
      },
      {
        label: 'পারিবারিক সম্পদ',
        data: familyWealth,
        backgroundColor: '#fbbf24',
        borderRadius: 4,
        barThickness: 20,
      },
    ];
    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">family_history</span>
        পারিবারিক সম্পদ বন্টন
      </h4>
      <div className="chart-container">
        <canvas ref={chartRef}></canvas>
      </div>
      <p className="text-xs text-gray-400 mt-4 text-center">
        * প্রার্থী বনাম পরিবারের সম্পদের অনুপাত
      </p>
    </div>
  );
};
