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 AssetMixChart = ({ 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: 'doughnut',
          data: { labels: [], datasets: [] },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                position: 'right',
                labels: {
                  font: { family: "'Hind Siliguri', sans-serif", size: 10 },
                  boxWidth: 10,
                  usePointStyle: true,
                },
              },
              tooltip: {
                callbacks: {
                  label: (ctx: any) =>
                    ` ${ctx.label}: ${toBn(makeAmountShortar(ctx.raw).value)} ${makeAmountShortar(ctx.raw).type}`,
                },
                bodyFont: { family: "'Hind Siliguri', sans-serif", size: 11 },
              },
            },
            cutout: '60%',
          },
        });
      }
    }

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

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

    // For simplicity in this pie chart, we will just take the FIRST selected candidate
    // showing detailed mix for multiple candidates in one pie is confusing.
    // Or we could aggregate? Let's show the first candidate's mix for now or average?
    // Usually comparisons are side-by-side, but pie charts don't stack well.
    // Let's implement it as a "Average Asset Mix" of selected candidates or just show main components.

    // Better approach: Show aggregated mix of ALL selected candidates to see where their wealth is concentrated generally?
    // Or better yet, maybe this chart isn't ideal for direct comparison of 3 people in one go unless it's a stacked bar.
    // However, the legacy design had a Pie chart. Let's assume it visualizes the aggregate or average.

    const parse = (v: string | null | undefined) => (v ? parseFloat(v) : 0);

    let totalCash = 0;
    let totalBank = 0;
    let totalSavings = 0;
    let totalVehicles = 0;
    let totalGold = 0;
    let totalFurniture = 0;

    selectedData.forEach((c) => {
      const assets = c.candidate_movable_asset;
      if (assets) {
        totalCash += parse(assets.cash);
        totalBank += parse(assets.bank_balance);
        totalSavings +=
          parse(assets.bond_fix_deposit) +
          parse(assets.sharemarket) +
          parse(assets.insurance_trust);
        totalVehicles += parse(assets.vehicles);
        totalGold += parse(assets.gold);
        totalFurniture += parse(assets.electronics) + parse(assets.furnitures);
      }
    });

    chartInstance.current.data.labels = [
      'নগদ',
      'ব্যাংক জমা',
      'বন্ড/শেয়ার',
      'যানবাহন',
      'স্বর্ণ',
      'অন্যান্য',
    ];
    chartInstance.current.data.datasets = [
      {
        data: [totalCash, totalBank, totalSavings, totalVehicles, totalGold, totalFurniture],
        backgroundColor: [
          '#10b981', // emerald
          '#3b82f6', // blue
          '#8b5cf6', // violet
          '#f59e0b', // amber
          '#eab308', // yellow
          '#94a3b8', // slate
        ],
        borderWidth: 0,
      },
    ];

    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-blue-500 text-lg">pie_chart</span>
        অস্থাবর সম্পদের প্রকৃতি
      </h4>
      <div className="chart-container">
        <canvas ref={chartRef}></canvas>
      </div>
      <p className="text-xs text-gray-400 mt-4 text-center">* নির্বাচিত প্রার্থীদের সম্মিলিত গড়</p>
    </div>
  );
};
