import Chart from '@/lib/chartjs-config';
import { DemographicsData } from '@/lib/db/comparision';
import { toBn } from '@/lib/utils';
import { useEffect, useRef } from 'react';

interface DemographicsSectionProps {
  demographicsData: DemographicsData;
}

export const DemographicsSection = ({ demographicsData }: DemographicsSectionProps) => {
  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: demographicsData.ageGroups.map((g) => `${toBn(g.range)} (${toBn(g.percent)}%)`),
            datasets: [
              {
                data: demographicsData.ageGroups.map((g) => g.percent),
                backgroundColor: ['#3b82f6', '#93c5fd', '#f59e0b', '#fbbf24', '#10b981', '#f87171'],
                borderWidth: 0,
              },
            ],
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            cutout: '65%',
          },
        });
      }
    }

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

  return (
    <>
      <div className="mt-12 pt-12 border-t border-blue-100 flex items-center justify-between mb-4">
        <h3 className="text-base md:text-xl font-bold text-blue-900 border-l-4 border-blue-500 pl-2">
          ভোটার ডেমোগ্রাফিক্স ও বিশ্লেষণ
        </h3>
      </div>

      {/* Demographics Block */}
      <div id="demographics-section" className="mb-4 space-y-4">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-4">
          {/* Chart Column */}
          <div className="lg:col-span-4 bg-white p-4 rounded-2xl shadow-sm border border-blue-100 flex flex-col items-start">
            <h4 className="text-sm font-bold text-blue-900 mb-4 w-full">
              বয়স ভিত্তিক ভোটার বিভাজন
            </h4>
            <div className="h-28 md:h-48 w-full relative mb-4">
              <canvas ref={chartRef}></canvas>
            </div>
            {/* Custom Legend */}
            <div id="demographics-legend" className="w-full space-y-2 mt-2">
              {demographicsData.ageGroups.map((g, i) => {
                const colors = ['#3b82f6', '#93c5fd', '#f59e0b', '#fbbf24', '#10b981', '#f87171'];
                return (
                  <div
                    key={i}
                    className="flex items-center justify-between py-1 border-b border-gray-50 last:border-0 hover:bg-blue-50/50 px-2 rounded-lg transition-colors"
                  >
                    <div className="flex items-center gap-3">
                      <span
                        className="w-3 h-3 rounded-sm shadow-sm"
                        style={{ backgroundColor: colors[i] }}
                      ></span>
                      <span className="text-sm text-gray-600 font-medium">{toBn(g.range)} বছর</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-bold text-blue-900">{toBn(g.percent)}%</span>
                      <span className="text-[10px] text-gray-400">
                        ({toBn(g.total.toLocaleString())} জন)
                      </span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Summary Table Column */}
          <div className="lg:col-span-8 bg-white p-2 rounded-2xl shadow-sm border border-blue-100 overflow-hidden">
            <h4 className="text-xs font-bold text-blue-900 mb-2 px-2">
              বয়স সীমা ও লিঙ্গ ভিত্তিক তথ্য
            </h4>
            <div className="overflow-x-auto">
              <table className="w-full text-[11px] md:text-sm">
                <thead className="bg-slate-50 text-blue-950 border-b-2 border-blue-100">
                  <tr>
                    <th className="p-1 md:p-2">বয়স সীমা</th>
                    <th className="p-1 md:p-2">পুরুষ</th>
                    <th className="p-1 md:p-2">মহিলা</th>
                    <th className="p-1 md:p-2">অন্যান্য</th>
                    <th className="p-1 md:p-2 bg-blue-50">মোট</th>
                  </tr>
                </thead>
                <tbody id="demographics-table-body" className="divide-y divide-blue-50">
                  {demographicsData.ageGroups.map((g, i) => (
                    <tr key={i} className="hover:bg-blue-50 transition-colors">
                      <td className="p-1 md:p-2 text-center font-bold text-blue-950 border-r border-blue-100 bg-slate-100/50">
                        {toBn(g.range)}
                      </td>
                      <td className="p-1 md:p-2 text-center text-gray-700 border-r border-blue-100">
                        {toBn(g.male.toLocaleString())}{' '}
                        <span className="text-[10px] text-gray-400">
                          ({toBn(((g.male / g.total) * 100).toFixed(1))}%)
                        </span>
                      </td>
                      <td className="p-1 md:p-2 text-center text-gray-700 border-r border-blue-100">
                        {toBn(g.female.toLocaleString())}{' '}
                        <span className="text-[10px] text-gray-400">
                          ({toBn(((g.female / g.total) * 100).toFixed(1))}%)
                        </span>
                      </td>
                      <td className="p-1 md:p-2 text-center text-gray-700 border-r border-blue-100">
                        {toBn(g.others)}
                      </td>
                      <td className="p-1 md:p-2 text-center font-bold text-blue-900 bg-blue-50">
                        {toBn(g.total.toLocaleString())}{' '}
                        <span className="text-[10px] text-blue-600">({toBn(g.percent)}%)</span>
                      </td>
                    </tr>
                  ))}
                  <tr className="bg-blue-900 text-white font-bold">
                    <td className="p-1 md:p-2 text-center">মোট</td>
                    <td className="p-1 md:p-2 text-center">
                      {toBn(demographicsData.totals.male.toLocaleString())} ({toBn('53.0')}
                      %)
                    </td>
                    <td className="p-1 md:p-2 text-center">
                      {toBn(demographicsData.totals.female.toLocaleString())} ({toBn('47.0')}
                      %)
                    </td>
                    <td className="p-1 md:p-2 text-center">
                      {toBn(demographicsData.totals.others)}
                    </td>
                    <td className="p-1 md:p-2 text-center bg-yellow-500 text-blue-950">
                      {toBn(demographicsData.totals.total.toLocaleString())} ({toBn('100')}
                      %)
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>

        {/* Youth Breakdown */}
        <div className="bg-white p-3 rounded-2xl shadow-sm border border-blue-100">
          <h4 className="text-xs font-bold text-blue-900 mb-2">
            তরুণ ভোটারদের বিস্তারিত (১৮-২৪ বছর)
          </h4>
          <div className="overflow-x-auto">
            <table className="w-full text-xs">
              <thead className="bg-slate-50 text-blue-950 border-b border-blue-100">
                <tr>
                  <th className="py-1 px-2 border-r border-blue-100">বয়স</th>
                  <th className="py-1 px-2 border-r border-blue-100">পুরুষ</th>
                  <th className="py-1 px-2 border-r border-blue-100">মহিলা</th>
                  <th className="py-1 px-2 bg-blue-50">মোট</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-blue-50">
                {demographicsData.youthBreakdown.map((g, i) => (
                  <tr key={i} className="hover:bg-blue-50 transition-colors">
                    <td className="py-1 px-2 text-center font-bold text-blue-950 border-r border-blue-100 bg-slate-50">
                      {toBn(g.age)}
                    </td>
                    <td className="py-1 px-2 text-center text-gray-700 border-r border-blue-100">
                      {toBn(g.male.toLocaleString())}
                    </td>
                    <td className="py-1 px-2 text-center text-gray-700 border-r border-blue-100">
                      {toBn(g.female.toLocaleString())}
                    </td>
                    <td className="py-1 px-2 text-center font-bold text-blue-900 bg-blue-50">
                      {toBn(g.total.toLocaleString())}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </>
  );
};
