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 LiabilitiesChart = ({ 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: true,
                position: 'bottom',
                labels: {
                  font: { family: "'Hind Siliguri', sans-serif", size: 10 },
                  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 },
              },
            },
            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);
    const parse = (v: string | null | undefined) => (v ? parseFloat(v) : 0);

    const bankLoans = selectedData.map(
      (c) => parse(c.liabilities?.personal_loan) + parse(c.liabilities?.credit_master_card), // Assuming this implies bank related
    );
    const otherDebts = selectedData.map(
      (c) => parse(c.liabilities?.other_liabilities) + parse(c.liabilities?.income_tax), // Grouping others
    );

    chartInstance.current.data.labels = labels;
    chartInstance.current.data.datasets = [
      {
        label: 'ব্যাংক/ব্যক্তিগত ঋণ',
        data: bankLoans,
        backgroundColor: '#64748b',
        borderRadius: 4,
        barThickness: 15,
      },
      {
        label: 'অন্যান্য দায়',
        data: otherDebts,
        backgroundColor: '#94a3b8',
        borderRadius: 4,
        barThickness: 15,
      },
    ];
    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-gray-500 text-lg">account_balance</span>
        ঋণ ও দায়ের পরিমাণ
      </h4>
      <div className="chart-container">
        <canvas ref={chartRef}></canvas>
      </div>
      <p className="text-xs text-gray-400 mt-4 text-center">* ব্যাংক ঋণ ও ব্যক্তিগত দায়</p>
    </div>
  );
};
