import { toBn } from '@/lib/utils';
import Chart from 'chart.js/auto';
import { useEffect, useRef } from 'react';
import type { DemographicsCardProps } from '../../seat.type';

export function DemographicsCard({ totalVoters }: DemographicsCardProps) {
  const voterGenderChartRef = useRef<HTMLCanvasElement>(null);
  const voterAgeChartRef = useRef<HTMLCanvasElement>(null);
  const genderChartInstance = useRef<Chart | null>(null);
  const ageChartInstance = useRef<Chart | null>(null);

  useEffect(() => {
    // Destroy existing charts
    if (genderChartInstance.current) {
      genderChartInstance.current.destroy();
    }
    if (ageChartInstance.current) {
      ageChartInstance.current.destroy();
    }

    const male = Math.floor(totalVoters * 0.51);
    const female = totalVoters - male;

    // Gender Chart
    if (voterGenderChartRef.current) {
      genderChartInstance.current = new Chart(voterGenderChartRef.current, {
        type: 'doughnut',
        data: {
          labels: ['পুরুষ', 'মহিলা'],
          datasets: [
            {
              data: [male, female],
              backgroundColor: ['#3b82f6', '#ec4899'],
              borderWidth: 0,
              hoverOffset: 4,
            },
          ],
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              position: 'right',
              labels: { font: { family: "'Hind Siliguri', sans-serif" }, boxWidth: 12 },
            },
          },
          cutout: '75%',
        },
      });
    }

    // Age Chart
    if (voterAgeChartRef.current) {
      ageChartInstance.current = new Chart(voterAgeChartRef.current, {
        type: 'bar',
        data: {
          labels: ['১৮-২৫', '২৬-৩৫', '৩৬-৫০', '৫০+'],
          datasets: [
            {
              label: 'ভোটার সংখ্যা',
              data: [
                Math.floor(totalVoters * 0.25),
                Math.floor(totalVoters * 0.3),
                Math.floor(totalVoters * 0.25),
                Math.floor(totalVoters * 0.2),
              ],
              backgroundColor: '#10b981',
              borderRadius: 4,
            },
          ],
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: { legend: { display: false } },
          scales: {
            y: { display: false },
            x: {
              grid: { display: false },
              ticks: { font: { family: "'Hind Siliguri', sans-serif" } },
            },
          },
        },
      });
    }

    return () => {
      if (genderChartInstance.current) {
        genderChartInstance.current.destroy();
      }
      if (ageChartInstance.current) {
        ageChartInstance.current.destroy();
      }
    };
  }, [totalVoters]);

  return (
    <div className="bg-white rounded-2xl shadow-sm border border-slate-200 p-6">
      <h3 className="text-sm font-bold text-slate-800 mb-4 uppercase tracking-wider">
        ভোটার বিশ্লেষণ
      </h3>

      {/* Gender */}
      <div className="relative h-40 mb-6">
        <canvas ref={voterGenderChartRef}></canvas>
      </div>
      <div className="grid grid-cols-2 gap-2 mb-6 text-center">
        <div className="p-2 bg-blue-50 rounded border border-blue-100">
          <p className="text-xs text-slate-500">পুরুষ</p>
          <p className="font-bold text-blue-700">
            {toBn(Math.floor(totalVoters * 0.51).toLocaleString())}
          </p>
        </div>
        <div className="p-2 bg-pink-50 rounded border border-pink-100">
          <p className="text-xs text-slate-500">মহিলা</p>
          <p className="font-bold text-pink-700">
            {toBn(Math.floor(totalVoters * 0.49).toLocaleString())}
          </p>
        </div>
      </div>

      {/* Age Groups */}
      <h4 className="text-xs font-bold text-slate-400 mb-3 uppercase border-t border-slate-100 pt-4">
        বয়স ভিত্তিক ভোটার
      </h4>
      <div className="relative h-40">
        <canvas ref={voterAgeChartRef}></canvas>
      </div>
    </div>
  );
}
