'use client';

import React, { useState, useMemo } from 'react';
import {
  X,
  Users,
  Search,
  Filter,
  ArrowUpDown,
  Download,
  Printer,
  CheckCircle2,
  MapPin,
  TrendingUp,
  Building,
  ShieldCheck,
  Calendar,
  Layers,
  FileSpreadsheet,
  Award
} from 'lucide-react';
import { NIGERIAN_STATES, GEOPOLITICAL_ZONES } from '@/lib/electoralData';
import { StateItem, GeopoliticalZone } from '@/types';

interface Oct2026VoterRegisterModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSelectState?: (state: StateItem) => void;
}

export const Oct2026VoterRegisterModal: React.FC<Oct2026VoterRegisterModalProps> = ({
  isOpen,
  onClose,
  onSelectState,
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedZone, setSelectedZone] = useState<string>('ALL');
  const [sortBy, setSortBy] = useState<'VOTERS_DESC' | 'VOTERS_ASC' | 'GROWTH' | 'NAME'>('VOTERS_DESC');

  // National Summary Totals
  const nationalTotal2026 = useMemo(() => {
    return NIGERIAN_STATES.reduce((acc, s) => acc + s.registered_voters, 0);
  }, []);

  const nationalTotal2023 = useMemo(() => {
    return NIGERIAN_STATES.reduce((acc, s) => acc + (s.voters_2023 || s.registered_voters * 0.9), 0);
  }, []);

  const totalCvrGrowth = nationalTotal2026 - nationalTotal2023;
  const growthPercentage = ((totalCvrGrowth / nationalTotal2023) * 100).toFixed(2);

  // Zonal Totals Calculation
  const zonalBreakdown = useMemo(() => {
    return GEOPOLITICAL_ZONES.map((zone) => {
      const zoneStates = NIGERIAN_STATES.filter((s) => s.geopolitical_zone === zone.code);
      const voters = zoneStates.reduce((acc, s) => acc + s.registered_voters, 0);
      const voters2023 = zoneStates.reduce((acc, s) => acc + (s.voters_2023 || 0), 0);
      const share = ((voters / nationalTotal2026) * 100).toFixed(1);
      return {
        ...zone,
        voters,
        voters2023,
        growth: voters - voters2023,
        share,
        statesCount: zoneStates.length,
      };
    }).sort((a, b) => b.voters - a.voters);
  }, [nationalTotal2026]);

  // Filtered & Sorted State Table Data
  const filteredStates = useMemo(() => {
    return NIGERIAN_STATES.filter((s) => {
      const matchesSearch =
        s.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        s.geopolitical_zone.toLowerCase().includes(searchQuery.toLowerCase());
      const matchesZone = selectedZone === 'ALL' || s.geopolitical_zone === selectedZone;
      return matchesSearch && matchesZone;
    }).sort((a, b) => {
      if (sortBy === 'VOTERS_DESC') return b.registered_voters - a.registered_voters;
      if (sortBy === 'VOTERS_ASC') return a.registered_voters - b.registered_voters;
      if (sortBy === 'GROWTH') return (b.cvr_growth || 0) - (a.cvr_growth || 0);
      if (sortBy === 'NAME') return a.name.localeCompare(b.name);
      return 0;
    });
  }, [searchQuery, selectedZone, sortBy]);

  if (!isOpen) return null;

  // Export CSV Handler
  const handleExportCsv = () => {
    const headers = ['Rank', 'State Name', 'Geopolitical Zone', 'Oct 2026 Voters', '2023 Voters', 'Net CVR Growth', '% Share', 'LGAs', 'Wards', 'Polling Units'];
    const rows = filteredStates.map((s, idx) => [
      idx + 1,
      `"${s.name}"`,
      `"${s.geopolitical_zone}"`,
      s.registered_voters,
      s.voters_2023 || 0,
      s.cvr_growth || 0,
      `${((s.registered_voters / nationalTotal2026) * 100).toFixed(2)}%`,
      s.total_lgas,
      s.total_wards,
      s.total_pus,
    ]);

    const csvContent = 'data:text/csv;charset=utf-8,' + [headers.join(','), ...rows.map((e) => e.join(','))].join('\n');
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement('a');
    link.setAttribute('href', encodedUri);
    link.setAttribute('download', `INEC_Certified_Voter_Register_October_2026.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/80 backdrop-blur-md p-4 overflow-y-auto">
      <div className="bg-slate-900 border border-emerald-500/40 rounded-2xl w-full max-w-7xl shadow-2xl overflow-hidden my-6 max-h-[92vh] flex flex-col">
        {/* Header Bar */}
        <div className="bg-gradient-to-r from-emerald-950 via-slate-900 to-emerald-950 border-b border-emerald-500/30 p-6 flex flex-wrap items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <div className="p-3 bg-emerald-500/15 border border-emerald-400/30 rounded-xl text-emerald-400">
              <Users className="w-7 h-7" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <span className="bg-emerald-500/20 text-emerald-300 border border-emerald-400/40 text-xs px-2.5 py-0.5 rounded-full font-bold uppercase tracking-wider">
                  Official INEC Certified Dataset
                </span>
                <span className="text-slate-400 text-xs flex items-center gap-1">
                  <Calendar className="w-3.5 h-3.5" /> October 2026 Release
                </span>
              </div>
              <h2 className="text-2xl font-black text-white tracking-wide mt-1">
                National Register of Voters (October 2026)
              </h2>
            </div>
          </div>

          <div className="flex items-center gap-3">
            <button
              onClick={handleExportCsv}
              className="flex items-center gap-2 bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-sm px-4 py-2 rounded-xl transition-all shadow-lg shadow-emerald-900/30"
            >
              <Download className="w-4 h-4" /> Export CSV Data
            </button>
            <button
              onClick={() => window.print()}
              className="flex items-center gap-2 bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-700 font-semibold text-sm px-3.5 py-2 rounded-xl transition-all"
            >
              <Printer className="w-4 h-4" /> Print
            </button>
            <button
              onClick={onClose}
              className="p-2 text-slate-400 hover:text-white hover:bg-slate-800 rounded-xl transition-all"
            >
              <X className="w-6 h-6" />
            </button>
          </div>
        </div>

        {/* Scrollable Modal Body */}
        <div className="p-6 overflow-y-auto space-y-6 flex-1 text-slate-200">
          {/* Key National Stat Cards */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="bg-slate-800/80 border border-emerald-500/30 rounded-xl p-4 relative overflow-hidden shadow-md">
              <div className="absolute top-0 right-0 w-24 h-24 bg-emerald-500/10 rounded-full blur-xl -mr-6 -mt-6"></div>
              <p className="text-slate-400 text-xs font-bold uppercase tracking-wider">Total Registered Voters (2026)</p>
              <p className="text-3xl font-black text-emerald-400 mt-1">
                {nationalTotal2026.toLocaleString()}
              </p>

              <div className="flex items-center justify-between mt-3 text-xs border-t border-slate-700/60 pt-2">
                <span className="text-slate-400">2023 Register:</span>
                <span className="font-semibold text-slate-300">{nationalTotal2023.toLocaleString()}</span>
              </div>
            </div>

            <div className="bg-slate-800/80 border border-purple-500/30 rounded-xl p-4 relative overflow-hidden shadow-md">
              <div className="absolute top-0 right-0 w-24 h-24 bg-purple-500/10 rounded-full blur-xl -mr-6 -mt-6"></div>
              <p className="text-slate-400 text-xs font-bold uppercase tracking-wider">Net CVR New Registrations</p>
              <p className="text-3xl font-black text-purple-400 mt-1 flex items-center gap-1.5">
                +{totalCvrGrowth.toLocaleString()}
                <span className="text-xs bg-purple-500/20 text-purple-300 px-2 py-0.5 rounded-md border border-purple-400/30 font-medium">
                  +{growthPercentage}%
                </span>
              </p>
              <div className="flex items-center justify-between mt-3 text-xs border-t border-slate-700/60 pt-2">
                <span className="text-slate-400">Continuous Registration:</span>
                <span className="font-semibold text-slate-300">Phase 1 - 3 Cleaned (ABIS)</span>
              </div>
            </div>

            <div className="bg-slate-800/80 border border-blue-500/30 rounded-xl p-4 relative overflow-hidden shadow-md">
              <div className="absolute top-0 right-0 w-24 h-24 bg-blue-500/10 rounded-full blur-xl -mr-6 -mt-6"></div>
              <p className="text-slate-400 text-xs font-bold uppercase tracking-wider">Gender & Demographics</p>
              <p className="text-xl font-bold text-white mt-1">
                <span className="text-pink-400">52.8M Female (51.1%)</span>
              </p>
              <p className="text-sm font-semibold text-blue-400">
                50.6M Male (48.9%)
              </p>
              <div className="flex items-center justify-between mt-2 text-xs border-t border-slate-700/60 pt-2">
                <span className="text-slate-400">Youth (18-34 yrs):</span>
                <span className="font-semibold text-amber-400">41.37M (40.0%)</span>
              </div>
            </div>

            <div className="bg-slate-800/80 border border-amber-500/30 rounded-xl p-4 relative overflow-hidden shadow-md">
              <div className="absolute top-0 right-0 w-24 h-24 bg-amber-500/10 rounded-full blur-xl -mr-6 -mt-6"></div>
              <p className="text-slate-400 text-xs font-bold uppercase tracking-wider">PVC Collection Status</p>
              <p className="text-lg font-bold text-amber-300 mt-1 flex items-center gap-1">
                <CheckCircle2 className="w-5 h-5 text-emerald-400" /> Oct 9 - Dec 15, 2026
              </p>
              <p className="text-xs text-slate-300 mt-1">
                Collection active at 8,809 Wards & 774 LGAs
              </p>
              <div className="flex items-center justify-between mt-2 text-xs border-t border-slate-700/60 pt-2">
                <span className="text-slate-400">Registered PWDs:</span>
                <span className="font-semibold text-slate-200">85,200 Voters</span>
              </div>
            </div>
          </div>

          {/* Top 10 Battleground States Highlight */}
          <div className="bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 border border-slate-700 rounded-xl p-4">
            <div className="flex items-center justify-between mb-3">
              <h3 className="text-sm font-bold text-slate-200 uppercase tracking-wider flex items-center gap-2">
                <Award className="w-4 h-4 text-emerald-400" /> Top 10 High-Volume Voter States (October 2026)
              </h3>
              <span className="text-xs text-slate-400">Accounting for ~43% of total national vote</span>
            </div>
            <div className="grid grid-cols-2 sm:grid-cols-5 gap-2.5">
              {[...NIGERIAN_STATES]
                .sort((a, b) => b.registered_voters - a.registered_voters)
                .slice(0, 10)
                .map((st, rank) => (
                  <div
                    key={st.id}
                    onClick={() => onSelectState && onSelectState(st)}
                    className="bg-slate-950/70 border border-slate-700/70 hover:border-emerald-500/60 p-2.5 rounded-lg cursor-pointer transition-all hover:scale-[1.02]"
                  >
                    <div className="flex items-center justify-between">
                      <span className="text-xs font-black text-emerald-400 bg-emerald-950/60 px-1.5 py-0.5 rounded border border-emerald-500/30">
                        #{rank + 1}
                      </span>
                      <span className="text-[10px] text-slate-400">{st.geopolitical_zone.replace('_', ' ')}</span>
                    </div>
                    <p className="font-bold text-slate-100 text-sm mt-1 truncate">{st.name}</p>
                    <p className="text-xs font-extrabold text-emerald-300">
                      {st.registered_voters.toLocaleString()}
                    </p>
                    <p className="text-[10px] text-purple-300 mt-0.5">
                      +{(st.cvr_growth || 0).toLocaleString()} CVR
                    </p>
                  </div>
                ))}
            </div>
          </div>

          {/* Geopolitical Zonal Breakdown Cards */}
          <div>
            <h3 className="text-sm font-bold text-slate-200 uppercase tracking-wider mb-3 flex items-center gap-2">
              <Layers className="w-4 h-4 text-purple-400" /> Geopolitical Zonal Distribution Summary
            </h3>
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
              {zonalBreakdown.map((z) => (
                <button
                  key={z.code}
                  onClick={() => setSelectedZone(selectedZone === z.code ? 'ALL' : z.code)}
                  className={`text-left p-3 rounded-xl border transition-all ${
                    selectedZone === z.code
                      ? 'bg-purple-950/60 border-purple-400 shadow-lg shadow-purple-900/40 ring-1 ring-purple-400'
                      : 'bg-slate-800/60 border-slate-700 hover:border-slate-600'
                  }`}
                >
                  <p className="text-xs font-bold text-slate-300 truncate">{z.name}</p>
                  <p className="text-lg font-black text-purple-300 mt-0.5">
                    {z.voters.toLocaleString()}
                  </p>
                  <div className="flex items-center justify-between text-[11px] text-slate-400 mt-1">
                    <span>{z.statesCount} States</span>
                    <span className="font-bold text-emerald-400">{z.share}%</span>
                  </div>
                </button>
              ))}
            </div>
          </div>

          {/* Search, Filter & Sort Controls */}
          <div className="bg-slate-800/90 border border-slate-700 p-4 rounded-xl flex flex-wrap items-center justify-between gap-4">
            <div className="flex items-center gap-3 flex-1 min-w-[280px]">
              <div className="relative flex-1">
                <Search className="w-4 h-4 absolute left-3 top-3 text-slate-400" />
                <input
                  type="text"
                  placeholder="Search state name or zone..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full bg-slate-900 border border-slate-700 rounded-lg pl-9 pr-4 py-2 text-sm text-slate-100 placeholder-slate-400 focus:outline-none focus:border-emerald-500"
                />
              </div>

              <div className="flex items-center gap-2">
                <Filter className="w-4 h-4 text-slate-400" />
                <select
                  value={selectedZone}
                  onChange={(e) => setSelectedZone(e.target.value)}
                  className="bg-slate-900 border border-slate-700 rounded-lg px-3 py-2 text-sm text-slate-200 focus:outline-none focus:border-emerald-500"
                >
                  <option value="ALL">All Zones (36 States + FCT)</option>
                  {GEOPOLITICAL_ZONES.map((z) => (
                    <option key={z.code} value={z.code}>
                      {z.name}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            <div className="flex items-center gap-2">
              <ArrowUpDown className="w-4 h-4 text-slate-400" />
              <span className="text-xs text-slate-400 font-semibold">Sort By:</span>
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value as any)}
                className="bg-slate-900 border border-slate-700 rounded-lg px-3 py-2 text-sm text-slate-200 focus:outline-none focus:border-emerald-500"
              >
                <option value="VOTERS_DESC">Voters (Highest First)</option>
                <option value="VOTERS_ASC">Voters (Lowest First)</option>
                <option value="GROWTH">CVR Net Growth (+)</option>
                <option value="NAME">State Name (A - Z)</option>
              </select>
            </div>
          </div>

          {/* Interactive State-by-State Registered Voters Table */}
          <div className="border border-slate-700 rounded-xl overflow-hidden bg-slate-950/60 shadow-xl">
            <div className="overflow-x-auto">
              <table className="w-full text-left text-sm border-collapse">
                <thead>
                  <tr className="bg-slate-900 border-b border-slate-700 text-slate-300 font-bold uppercase text-xs tracking-wider">
                    <th className="py-3 px-4 w-12 text-center">Rank</th>
                    <th className="py-3 px-4">State Name</th>
                    <th className="py-3 px-4">Geopolitical Zone</th>
                    <th className="py-3 px-4 text-right">Oct 2026 Register</th>
                    <th className="py-3 px-4 text-right">2023 Register</th>
                    <th className="py-3 px-4 text-right">Net CVR Growth</th>
                    <th className="py-3 px-4 text-center">% Nat. Share</th>
                    <th className="py-3 px-4 text-center">LGAs</th>
                    <th className="py-3 px-4 text-center">Wards</th>
                    <th className="py-3 px-4 text-center">Polling Units</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-800/80">
                  {filteredStates.map((st, idx) => {
                    const share = ((st.registered_voters / nationalTotal2026) * 100).toFixed(2);
                    const cvrGrowth = st.cvr_growth || 0;
                    const v2023 = st.voters_2023 || Math.round(st.registered_voters * 0.9);

                    return (
                      <tr
                        key={st.id}
                        onClick={() => onSelectState && onSelectState(st)}
                        className="hover:bg-slate-800/60 transition-colors cursor-pointer group"
                      >
                        <td className="py-3 px-4 text-center font-bold text-slate-400 group-hover:text-emerald-400">
                          #{idx + 1}
                        </td>
                        <td className="py-3 px-4 font-extrabold text-white group-hover:text-emerald-300 flex items-center gap-2">
                          <MapPin className="w-3.5 h-3.5 text-slate-500 group-hover:text-emerald-400" />
                          {st.name}
                        </td>
                        <td className="py-3 px-4 text-slate-300">
                          <span className="text-xs bg-slate-800 border border-slate-700 px-2 py-0.5 rounded-full">
                            {st.geopolitical_zone.replace('_', ' ')}
                          </span>
                        </td>
                        <td className="py-3 px-4 text-right font-black text-emerald-400">
                          {st.registered_voters.toLocaleString()}
                        </td>
                        <td className="py-3 px-4 text-right text-slate-400 font-medium">
                          {v2023.toLocaleString()}
                        </td>
                        <td className="py-3 px-4 text-right font-bold text-purple-400">
                          +{cvrGrowth.toLocaleString()}
                        </td>
                        <td className="py-3 px-4 text-center">
                          <span className="text-xs font-bold text-amber-300 bg-amber-950/40 border border-amber-500/30 px-2 py-0.5 rounded-full">
                            {share}%
                          </span>
                        </td>
                        <td className="py-3 px-4 text-center text-slate-300 font-medium">{st.total_lgas}</td>
                        <td className="py-3 px-4 text-center text-slate-300 font-medium">{st.total_wards}</td>
                        <td className="py-3 px-4 text-center font-bold text-slate-200">
                          {st.total_pus.toLocaleString()}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
            {filteredStates.length === 0 && (
              <div className="p-8 text-center text-slate-400">
                No states matched your query "{searchQuery}".
              </div>
            )}
          </div>
        </div>

        {/* Modal Footer */}
        <div className="bg-slate-900 border-t border-slate-800 p-4 flex flex-wrap items-center justify-between gap-4 text-xs text-slate-400">
          <div className="flex items-center gap-2">
            <ShieldCheck className="w-4 h-4 text-emerald-400" />
            <span>
              Certified dataset compiled in accordance with Section 10 & 16 of Electoral Act 2022.
            </span>
          </div>
          <button
            onClick={onClose}
            className="bg-slate-800 hover:bg-slate-700 text-slate-200 font-bold px-5 py-2 rounded-xl border border-slate-700 transition-all"
          >
            Close Register Desk
          </button>
        </div>
      </div>
    </div>
  );
};
