'use client';

import React, { useState, useMemo } from 'react';
import {
  Search,
  X,
  ShieldCheck,
  Building,
  Map,
  Globe2,
  Lock,
  ArrowRight,
  Check,
  Copy,
  Users,
  KeyRound,
  Sparkles
} from 'lucide-react';
import { NIGERIAN_STATES, GEOPOLITICAL_ZONES } from '@/lib/electoralData';

interface AllCredentialsDirectoryModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSelectCredential: (identifier: string, pin: string) => void;
}

export function AllCredentialsDirectoryModal({
  isOpen,
  onClose,
  onSelectCredential,
}: AllCredentialsDirectoryModalProps) {
  const [searchTerm, setSearchTerm] = useState('');
  const [activeTab, setActiveTab] = useState<'ALL' | 'REGIONAL' | 'STATE' | 'LGA_WARD' | 'EXECUTIVE'>('ALL');
  const [copiedId, setCopiedId] = useState<string | null>(null);

  if (!isOpen) return null;

  // Generate All Official State Credentials (36 States + FCT Abuja)
  const stateCredentials = NIGERIAN_STATES.map((state) => ({
    id: `STATE-${state.id}`,
    category: 'STATE',
    title: `${state.name} State Supervisor Command`,
    identifier: `STATE-${state.id}`,
    pin: '1234',
    scopeName: `${state.name} State (${state.total_pus.toLocaleString()} PUs)`,
    zone: state.geopolitical_zone.replace(/_/g, ' '),
    badge: `State Code: ${state.id}`,
  }));

  // Generate All 6 Regional Credentials
  const regionalCredentials = GEOPOLITICAL_ZONES.map((zone) => ({
    id: `REGION-${zone.code}`,
    category: 'REGIONAL',
    title: `${zone.name} Zonal Command Director`,
    identifier: `REGION-${zone.code}`,
    pin: '1234',
    scopeName: `${zone.states.join(', ')}`,
    zone: zone.name,
    badge: `Zone: ${zone.code}`,
  }));

  // Executive Credentials
  const executiveCredentials = [
    {
      id: 'NAT-DIR-001',
      category: 'EXECUTIVE',
      title: 'National Campaign Headquarters Command',
      identifier: 'NAT-DIR-001',
      pin: '1234',
      scopeName: 'Federal Republic of Nigeria (Full Nationwide Overview)',
      zone: 'Abuja HQ',
      badge: 'National Director',
    },
    {
      id: 'GETOCORE-HQ-01',
      category: 'EXECUTIVE',
      title: 'GetoCore Technical Infrastructure Lead',
      identifier: 'GETOCORE-HQ-01',
      pin: '1234',
      scopeName: 'INEC IReV Scrapers & SHA-256 Vault Telemetry',
      zone: 'GetoCore Systems',
      badge: 'Tech Desk Lead',
    },
  ];

  // LGA & Ward Sample Credentials
  const lgaWardCredentials = [
    {
      id: 'LGA-24-11',
      category: 'LGA_WARD',
      title: 'Ikeja LGA Collation Supervisor (Lagos)',
      identifier: 'LGA-24-11',
      pin: '1234',
      scopeName: 'Ikeja LGA (666 Polling Units)',
      zone: 'South West',
      badge: 'LGA Supervisor',
    },
    {
      id: 'LGA-19-01',
      category: 'LGA_WARD',
      title: 'Kano Municipal LGA Collation Supervisor (Kano)',
      identifier: 'LGA-19-01',
      pin: '1234',
      scopeName: 'Kano Municipal LGA (850 Polling Units)',
      zone: 'North West',
      badge: 'LGA Supervisor',
    },
    {
      id: 'LGA-21-06',
      category: 'LGA_WARD',
      title: 'Birnin Kebbi LGA Collation Supervisor (Kebbi)',
      identifier: 'LGA-21-06',
      pin: '1234',
      scopeName: 'Birnin Kebbi LGA (178 Polling Units)',
      zone: 'North West',
      badge: 'LGA Supervisor',
    },
    {
      id: 'LGA-32-01',
      category: 'LGA_WARD',
      title: 'Port Harcourt LGA Collation Supervisor (Rivers)',
      identifier: 'LGA-32-01',
      pin: '1234',
      scopeName: 'Port Harcourt LGA (720 Polling Units)',
      zone: 'South South',
      badge: 'LGA Supervisor',
    },
    {
      id: 'LGA-37-01',
      category: 'LGA_WARD',
      title: 'AMAC LGA Collation Supervisor (FCT Abuja)',
      identifier: 'LGA-37-01',
      pin: '1234',
      scopeName: 'Abuja Municipal Area Council (940 Polling Units)',
      zone: 'North Central',
      badge: 'LGA Supervisor',
    },
    {
      id: 'WARD-24-11-01',
      category: 'LGA_WARD',
      title: 'Alausa Ward Registration Area Supervisor (Lagos)',
      identifier: 'WARD-24-11-01',
      pin: '1234',
      scopeName: 'Alausa Ward (35 Polling Units)',
      zone: 'South West',
      badge: 'RA / Ward Supervisor',
    },
    {
      id: 'WARD-19-01-01',
      category: 'LGA_WARD',
      title: 'Shahuchi Ward Registration Area Supervisor (Kano)',
      identifier: 'WARD-19-01-01',
      pin: '1234',
      scopeName: 'Shahuchi Ward (42 Polling Units)',
      zone: 'North West',
      badge: 'RA / Ward Supervisor',
    },
    {
      id: 'WARD-21-06-01',
      category: 'LGA_WARD',
      title: 'Nassarawa I Ward Registration Area Supervisor (Kebbi)',
      identifier: 'WARD-21-06-01',
      pin: '1234',
      scopeName: 'Nassarawa I Ward (28 Polling Units)',
      zone: 'North West',
      badge: 'RA / Ward Supervisor',
    },
    {
      id: '24-11-01-001',
      category: 'LGA_WARD',
      title: 'Accredited Field Polling Unit Agent (PU 001 Lagos)',
      identifier: '24-11-01-001',
      pin: '1234',
      scopeName: 'Governor Office Gate PU 001 (INEC Code: 24-11-01-001)',
      zone: 'Polling Unit Agent',
      badge: 'PU Agent',
    },
    {
      id: '19-11-01-004',
      category: 'LGA_WARD',
      title: 'Accredited Field Polling Unit Agent (PU 004 Kano)',
      identifier: '19-11-01-004',
      pin: '1234',
      scopeName: 'Gidan Sarki Primary School PU (INEC Code: 19-11-01-004)',
      zone: 'Polling Unit Agent',
      badge: 'PU Agent',
    },
  ];

  const allCredentials = useMemo(() => {
    return [
      ...executiveCredentials,
      ...regionalCredentials,
      ...stateCredentials,
      ...lgaWardCredentials,
    ];
  }, []);

  const filteredCredentials = useMemo(() => {
    return allCredentials.filter((cred) => {
      const matchesTab = activeTab === 'ALL' || cred.category === activeTab;
      const matchesSearch =
        cred.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        cred.identifier.toLowerCase().includes(searchTerm.toLowerCase()) ||
        cred.scopeName.toLowerCase().includes(searchTerm.toLowerCase()) ||
        cred.zone.toLowerCase().includes(searchTerm.toLowerCase());
      return matchesTab && matchesSearch;
    });
  }, [allCredentials, activeTab, searchTerm]);

  const handleCopy = (id: string, text: string) => {
    navigator.clipboard.writeText(text);
    setCopiedId(id);
    setTimeout(() => setCopiedId(null), 2000);
  };

  return (
    <div className="fixed inset-0 z-50 bg-slate-950/80 backdrop-blur-md flex items-center justify-center p-4 overflow-y-auto">
      <div className="bg-white border border-slate-200 rounded-3xl max-w-4xl w-full max-h-[90vh] flex flex-col shadow-2xl overflow-hidden">
        {/* Modal Header */}
        <div className="bg-emerald-950 text-white p-5 flex items-center justify-between border-b border-emerald-800 shrink-0">
          <div className="flex items-center gap-3">
            <div className="p-3 bg-amber-400 text-slate-950 rounded-2xl font-black">
              <KeyRound className="w-6 h-6" />
            </div>
            <div>
              <h3 className="text-base font-black text-white tracking-wide flex items-center gap-2">
                Official Command Credentials Directory
                <span className="text-[10px] px-2 py-0.5 rounded-full bg-emerald-900 text-amber-300 border border-emerald-700 font-bold">
                  36 States + FCT &bull; Default PIN: 1234
                </span>
              </h3>
              <p className="text-xs text-emerald-200 mt-0.5">
                Full list of login IDs for Regional Directors, State Supervisors, LGA Officers, Ward RAs, and PU Agents.
              </p>
            </div>
          </div>

          <button
            type="button"
            onClick={onClose}
            className="p-2 rounded-xl bg-emerald-900 hover:bg-emerald-800 text-slate-300 hover:text-white transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Search Bar & Category Filter Bar */}
        <div className="p-4 bg-slate-50 border-b border-slate-200 space-y-3 shrink-0">
          <div className="relative">
            <Search className="w-4 h-4 text-slate-400 absolute left-3.5 top-3" />
            <input
              type="text"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="Search by state name (e.g. Kano, Lagos, Rivers, FCT), zone, or ID code (e.g. STATE-20, REGION-NW)..."
              className="w-full bg-white border border-slate-300 rounded-xl pl-10 pr-4 py-2 text-xs font-semibold text-slate-900 focus:outline-none focus:border-emerald-600 shadow-xs"
            />
          </div>

          <div className="flex items-center gap-1.5 overflow-x-auto pb-1">
            <button
              onClick={() => setActiveTab('ALL')}
              className={`px-3 py-1.5 rounded-xl text-xs font-bold transition whitespace-nowrap ${
                activeTab === 'ALL'
                  ? 'bg-emerald-700 text-white shadow-xs'
                  : 'bg-white text-slate-600 hover:bg-slate-200 border border-slate-200'
              }`}
            >
              All Roles ({allCredentials.length})
            </button>
            <button
              onClick={() => setActiveTab('EXECUTIVE')}
              className={`px-3 py-1.5 rounded-xl text-xs font-bold transition whitespace-nowrap ${
                activeTab === 'EXECUTIVE'
                  ? 'bg-emerald-700 text-white shadow-xs'
                  : 'bg-white text-slate-600 hover:bg-slate-200 border border-slate-200'
              }`}
            >
              Executive Command (2)
            </button>
            <button
              onClick={() => setActiveTab('REGIONAL')}
              className={`px-3 py-1.5 rounded-xl text-xs font-bold transition whitespace-nowrap ${
                activeTab === 'REGIONAL'
                  ? 'bg-emerald-700 text-white shadow-xs'
                  : 'bg-white text-slate-600 hover:bg-slate-200 border border-slate-200'
              }`}
            >
              6 Geopolitical Regions
            </button>
            <button
              onClick={() => setActiveTab('STATE')}
              className={`px-3 py-1.5 rounded-xl text-xs font-bold transition whitespace-nowrap ${
                activeTab === 'STATE'
                  ? 'bg-emerald-700 text-white shadow-xs'
                  : 'bg-white text-slate-600 hover:bg-slate-200 border border-slate-200'
              }`}
            >
              36 States + FCT Abuja ({stateCredentials.length})
            </button>
            <button
              onClick={() => setActiveTab('LGA_WARD')}
              className={`px-3 py-1.5 rounded-xl text-xs font-bold transition whitespace-nowrap ${
                activeTab === 'LGA_WARD'
                  ? 'bg-emerald-700 text-white shadow-xs'
                  : 'bg-white text-slate-600 hover:bg-slate-200 border border-slate-200'
              }`}
            >
              LGAs, Wards &amp; PU Agents
            </button>
          </div>
        </div>

        {/* Credentials Grid List */}
        <div className="p-4 sm:p-5 overflow-y-auto flex-1 space-y-3">
          {filteredCredentials.length === 0 ? (
            <div className="text-center py-10 text-slate-500 space-y-2">
              <Search className="w-8 h-8 text-slate-400 mx-auto" />
              <p className="text-sm font-bold">No credentials matching &quot;{searchTerm}&quot;</p>
              <p className="text-xs">Try searching for a state name like &quot;Kano&quot; or code like &quot;STATE-20&quot;.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
              {filteredCredentials.map((item) => (
                <div
                  key={item.id}
                  className="bg-slate-50 border border-slate-200 hover:border-emerald-500/80 rounded-2xl p-4 shadow-xs transition space-y-3 flex flex-col justify-between"
                >
                  <div className="space-y-1.5">
                    <div className="flex items-center justify-between">
                      <span className="text-[10px] px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-800 font-mono font-bold">
                        {item.badge}
                      </span>
                      <span className="text-[10px] font-bold text-slate-500 font-mono">
                        PIN: <strong className="text-slate-900">{item.pin}</strong>
                      </span>
                    </div>

                    <h4 className="text-xs font-black text-slate-900">{item.title}</h4>
                    <p className="text-[11px] text-slate-500 font-medium">{item.scopeName}</p>
                  </div>

                  {/* Action Buttons: Copy ID & One-Click Login */}
                  <div className="pt-2 border-t border-slate-200 flex items-center justify-between gap-2">
                    <div className="flex items-center gap-1 bg-white px-2.5 py-1 rounded-lg border border-slate-300 font-mono text-[11px] text-slate-900 font-bold truncate">
                      <span>{item.identifier}</span>
                      <button
                        type="button"
                        onClick={() => handleCopy(item.id, item.identifier)}
                        className="text-slate-400 hover:text-slate-700 ml-1"
                        title="Copy ID"
                      >
                        {copiedId === item.id ? (
                          <Check className="w-3.5 h-3.5 text-emerald-600" />
                        ) : (
                          <Copy className="w-3.5 h-3.5" />
                        )}
                      </button>
                    </div>

                    <button
                      type="button"
                      onClick={() => {
                        onSelectCredential(item.identifier, item.pin);
                        onClose();
                      }}
                      className="px-3 py-1.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-black flex items-center gap-1.5 shadow-xs transition active:scale-95 shrink-0"
                    >
                      <span>Auto-Fill &amp; Login</span>
                      <ArrowRight className="w-3.5 h-3.5" />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Modal Footer */}
        <div className="p-4 bg-slate-100 border-t border-slate-200 text-slate-600 text-xs flex items-center justify-between font-bold shrink-0">
          <span>Security Notice: All official accounts protected by AES-256 + SHA-256 HMAC</span>
          <button
            type="button"
            onClick={onClose}
            className="px-4 py-1.5 rounded-xl bg-slate-800 hover:bg-slate-900 text-white text-xs font-bold transition"
          >
            Close Directory
          </button>
        </div>
      </div>
    </div>
  );
}
