import { District } from '@/lib/db/division';
import { toBn } from '@/lib/utils';
import { useEffect, useState } from 'react';

interface DistrictDetailsProps {
  selectedDistrict: District;
  selectedDivisionName?: string;
  onClose: () => void;
}

interface Upazila {
  name: string;
  centers: number;
  voters: number;
}

// Common upazila names for generation
const commonUpazilas = [
  'সদর',
  'পূর্ব',
  'পশ্চিম',
  'উত্তর',
  'দক্ষিণ',
  'কালীগঞ্জ',
  'রায়পুর',
  'সোনারগাঁও',
  'রূপগঞ্জ',
  'সাভার',
  'দোহার',
  'নবাবগঞ্জ',
  'কেরানীগঞ্জ',
];

function generateUpazilas(districtName: string, count: number = 5): Upazila[] {
  const upazilas: Upazila[] = [];

  // Always add Sadar first
  upazilas.push({
    name: `${districtName} সদর`,
    centers: 120 + Math.floor(Math.random() * 50),
    voters: 250000 + Math.floor(Math.random() * 50000),
  });

  for (let i = 1; i < count; i++) {
    const name = commonUpazilas[i] || `উপজেলা ${i + 1}`;
    const isGeneric = !commonUpazilas[i];
    const uName = isGeneric ? `${districtName} ${i + 1}` : commonUpazilas[i];

    upazilas.push({
      name: uName,
      centers: 50 + Math.floor(Math.random() * 100),
      voters: 100000 + Math.floor(Math.random() * 100000),
    });
  }

  return upazilas;
}

export const DistrictDetails = ({
  selectedDistrict,
  selectedDivisionName,
  onClose,
}: DistrictDetailsProps) => {
  const [upazilas, setUpazilas] = useState<Upazila[]>([]);

  useEffect(() => {
    if (selectedDistrict) {
      const count = 4 + Math.floor(Math.random() * 4);
      const generatedUpazilas = generateUpazilas(selectedDistrict.name, count);
      setUpazilas(generatedUpazilas);
    }
  }, [selectedDistrict]);

  const districtStats = {
    totalVoters: upazilas.reduce((sum, u) => sum + u.voters, 0),
    totalCenters: upazilas.reduce((sum, u) => sum + u.centers, 0),
    maleVoters: Math.floor(
      upazilas.reduce((sum, u) => sum + u.voters, 0) * (0.48 + Math.random() * 0.04),
    ),
    femaleVoters: 0,
  };
  districtStats.femaleVoters = districtStats.totalVoters - districtStats.maleVoters;

  return (
    <div className="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-gray-200 overflow-hidden mb-6 sm:mb-8 scroll-mt-20">
      {/* District Header */}
      <div className="bg-teal-50 border-b border-teal-100 p-4 sm:p-6 flex justify-between items-start sm:items-center flex-col sm:flex-row gap-4">
        <div>
          <h3 className="text-xl sm:text-2xl font-bold text-teal-900 flex items-center gap-2">
            <span className="material-symbols-outlined text-teal-600">map</span>
            {selectedDistrict.name} জেলা
          </h3>
          <div className="flex flex-wrap gap-2 mt-2">
            <span className="px-2 py-1 rounded-md bg-purple-100 text-purple-700 text-xs font-bold border border-purple-200">
              {toBn(selectedDistrict.al + selectedDistrict.jp + selectedDistrict.ind)}টি আসন
            </span>
            <span className="px-2 py-1 rounded-md bg-blue-100 text-blue-700 text-xs font-bold border border-blue-200">
              বিভাগ: {selectedDivisionName}
            </span>
          </div>
        </div>
        <button
          onClick={onClose}
          className="text-teal-600 hover:bg-teal-100 px-3 py-1 rounded-lg text-sm font-medium transition flex items-center gap-1"
        >
          <span className="material-symbols-outlined text-lg">close</span> বন্ধ করুন
        </button>
      </div>

      {/* District Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 p-4 sm:p-6 border-b border-gray-100">
        <div className="bg-blue-50 p-4 rounded-xl text-center">
          <p className="text-blue-600 text-xs font-bold uppercase mb-1">মোট ভোটার</p>
          <p className="text-xl font-bold text-gray-800">
            {toBn(districtStats.totalVoters.toLocaleString())}
          </p>
        </div>
        <div className="bg-pink-50 p-4 rounded-xl text-center">
          <p className="text-pink-600 text-xs font-bold uppercase mb-1">নারী ভোটার</p>
          <p className="text-xl font-bold text-gray-800">
            {toBn(districtStats.femaleVoters.toLocaleString())}
          </p>
        </div>
        <div className="bg-indigo-50 p-4 rounded-xl text-center">
          <p className="text-indigo-600 text-xs font-bold uppercase mb-1">পুরুষ ভোটার</p>
          <p className="text-xl font-bold text-gray-800">
            {toBn(districtStats.maleVoters.toLocaleString())}
          </p>
        </div>
        <div className="bg-green-50 p-4 rounded-xl text-center">
          <p className="text-green-600 text-xs font-bold uppercase mb-1">মোট কেন্দ্র</p>
          <p className="text-xl font-bold text-gray-800">{toBn(districtStats.totalCenters)}</p>
        </div>
      </div>

      {/* Upazila Breakdown Table */}
      <div className="overflow-x-auto">
        <table className="w-full text-xs sm:text-sm">
          <thead className="bg-gray-50 border-b border-gray-200">
            <tr>
              <th className="px-4 py-3 text-left font-bold text-gray-600">উপজেলা/থানা</th>
              <th className="px-4 py-3 text-center font-bold text-gray-600">কেন্দ্র</th>
              <th className="px-4 py-3 text-center font-bold text-gray-800">ভোটার</th>
              <th className="px-4 py-3 text-center font-bold text-blue-600">পুরুষ (%)</th>
              <th className="px-4 py-3 text-center font-bold text-pink-600">মহিলা (%)</th>
              <th className="px-4 py-3 text-center font-bold text-purple-600">বিজয়ী (সম্ভাব্য)</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {upazilas.map((upazila, index) => {
              const malePct = 48 + Math.random() * 4;
              const femalePct = 100 - malePct;
              const maleCnt = Math.round(upazila.voters * (malePct / 100));
              const femaleCnt = Math.round(upazila.voters * (femalePct / 100));

              // Random winner
              const r = Math.random();
              const winner =
                r > 0.4
                  ? {
                      name: 'আওয়ামী লীগ',
                      class: 'text-green-700 bg-green-50 border-green-200',
                    }
                  : r > 0.2
                    ? {
                        name: 'জাতীয় পার্টি',
                        class: 'text-red-700 bg-red-50 border-red-200',
                      }
                    : {
                        name: 'স্বতন্ত্র',
                        class: 'text-gray-700 bg-gray-50 border-gray-200',
                      };

              return (
                <tr
                  key={index}
                  className="hover:bg-gray-50 transition border-b border-gray-50 last:border-0"
                >
                  <td className="px-4 py-3 font-bold text-gray-800">{upazila.name}</td>
                  <td className="px-4 py-3 text-center text-gray-600">{toBn(upazila.centers)}</td>
                  <td className="px-4 py-3 text-center font-bold text-gray-800">
                    {toBn(upazila.voters.toLocaleString())}
                  </td>
                  <td className="px-4 py-3 text-center">
                    <div className="text-xs text-blue-600 font-bold">
                      {toBn(malePct.toFixed(1))}%
                    </div>
                    <div className="text-[10px] text-gray-400">
                      ({toBn(maleCnt.toLocaleString())})
                    </div>
                  </td>
                  <td className="px-4 py-3 text-center">
                    <div className="text-xs text-pink-600 font-bold">
                      {toBn(femalePct.toFixed(1))}%
                    </div>
                    <div className="text-[10px] text-gray-400">
                      ({toBn(femaleCnt.toLocaleString())})
                    </div>
                  </td>
                  <td className="px-4 py-3 text-center">
                    <span
                      className={`inline-flex items-center gap-1 px-2 py-1 rounded-full border text-[11px] font-bold ${winner.class}`}
                    >
                      {winner.name}
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};
