'use client';

import React, { useState } from 'react';
import {
  X,
  Send,
  RotateCcw,
  CheckCircle2,
  AlertTriangle,
  Zap,
  Building,
  MapPin,
  FileText,
  ShieldCheck,
  Check,
  Users
} from 'lucide-react';
import { PuResultData } from '@/types';

interface PresetPu {
  pu_code: string;
  pu_name: string;
  state_id: string;
  state_name: string;
  lga_name: string;
  ward_name: string;
  zone: string;
  registered_voters: number;
  defaultVotes: {
    adc: number;
    apc: number;
    pdp: number;
    lp: number;
    nnpp: number;
  };
}

const PRESET_PUS: PresetPu[] = [
  {
    pu_code: '19-11-01-004',
    pu_name: 'Gidan Sarki Primary School PU',
    state_id: '19',
    state_name: 'Kano',
    lga_name: 'Kano Municipal',
    ward_name: 'Zango',
    zone: 'North West (NW)',
    registered_voters: 750,
    defaultVotes: { adc: 385, apc: 120, pdp: 30, lp: 15, nnpp: 10 },
  },
  {
    pu_code: '18-09-02-011',
    pu_name: 'Kawo Primary School Polling Unit',
    state_id: '18',
    state_name: 'Kaduna',
    lga_name: 'Kaduna North',
    ward_name: 'Kawo',
    zone: 'North West (NW)',
    registered_voters: 680,
    defaultVotes: { adc: 340, apc: 145, pdp: 40, lp: 20, nnpp: 5 },
  },
  {
    pu_code: '21-06-01-003',
    pu_name: 'Shehu Shagari Model Primary School PU',
    state_id: '21',
    state_name: 'Kebbi',
    lga_name: 'Birnin Kebbi',
    ward_name: 'Nassarawa I',
    zone: 'North West (NW)',
    registered_voters: 640,
    defaultVotes: { adc: 325, apc: 110, pdp: 35, lp: 10, nnpp: 5 },
  },
  {
    pu_code: '20-01-01-002',
    pu_name: 'Emir Palace Gateway Polling Unit',
    state_id: '20',
    state_name: 'Katsina',
    lga_name: 'Katsina',
    ward_name: 'Wakilin Gabas',
    zone: 'North West (NW)',
    registered_voters: 710,
    defaultVotes: { adc: 360, apc: 160, pdp: 25, lp: 10, nnpp: 5 },
  },
  {
    pu_code: '24-11-01-001',
    pu_name: 'Governor Office Gate / Secretariat PU',
    state_id: '24',
    state_name: 'Lagos',
    lga_name: 'Ikeja',
    ward_name: 'Alausa',
    zone: 'South West (SW)',
    registered_voters: 720,
    defaultVotes: { adc: 290, apc: 210, pdp: 45, lp: 60, nnpp: 5 },
  },
  {
    pu_code: '32-15-01-008',
    pu_name: 'Town Hall Community Square PU',
    state_id: '32',
    state_name: 'Rivers',
    lga_name: 'Port Harcourt',
    ward_name: 'Ward 1 (Township)',
    zone: 'South South (SS)',
    registered_voters: 640,
    defaultVotes: { adc: 310, apc: 95, pdp: 80, lp: 35, nnpp: 0 },
  },
  {
    pu_code: '08-01-01-005',
    pu_name: 'Shehu Palace Gate Polling Unit',
    state_id: '08',
    state_name: 'Borno',
    lga_name: 'Maiduguri',
    ward_name: 'Shehuri North',
    zone: 'North East (NE)',
    registered_voters: 590,
    defaultVotes: { adc: 320, apc: 130, pdp: 25, lp: 10, nnpp: 5 },
  },
  {
    pu_code: '14-04-01-003',
    pu_name: 'Ogbete Market Square Polling Unit',
    state_id: '14',
    state_name: 'Enugu',
    lga_name: 'Enugu North',
    ward_name: 'Ward 3 (Market Area)',
    zone: 'South East (SE)',
    registered_voters: 610,
    defaultVotes: { adc: 275, apc: 60, pdp: 45, lp: 110, nnpp: 0 },
  },
  {
    pu_code: '37-06-01-002',
    pu_name: 'Garki Primary School Polling Unit',
    state_id: '37',
    state_name: 'FCT Abuja',
    lga_name: 'AMAC (Abuja Municipal)',
    ward_name: 'Garki Village',
    zone: 'North Central (NC)',
    registered_voters: 800,
    defaultVotes: { adc: 360, apc: 150, pdp: 50, lp: 80, nnpp: 10 },
  },
];

interface LivePuTransmissionTestModalProps {
  isOpen: boolean;
  onClose: () => void;
  onTransmissionComplete: (newResult: PuResultData) => void;
  onResetComplete: () => void;
  totalCurrentlySubmitted: number;
}

export function LivePuTransmissionTestModal({
  isOpen,
  onClose,
  onTransmissionComplete,
  onResetComplete,
  totalCurrentlySubmitted,
}: LivePuTransmissionTestModalProps) {
  const [selectedPresetIndex, setSelectedPresetIndex] = useState<number>(0);
  const currentPreset = PRESET_PUS[selectedPresetIndex];

  const [adcVotes, setAdcVotes] = useState<number>(currentPreset.defaultVotes.adc);
  const [apcVotes, setApcVotes] = useState<number>(currentPreset.defaultVotes.apc);
  const [pdpVotes, setPdpVotes] = useState<number>(currentPreset.defaultVotes.pdp);
  const [lpVotes, setLpVotes] = useState<number>(currentPreset.defaultVotes.lp);
  const [nnppVotes, setNnppVotes] = useState<number>(currentPreset.defaultVotes.nnpp);
  const [rejectedBallots, setRejectedBallots] = useState<number>(0);

  const [agentName, setAgentName] = useState<string>('Malam Haruna Bello (Accredited Agent)');
  const [isTransmitting, setIsTransmitting] = useState<boolean>(false);
  const [statusMessage, setStatusMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  if (!isOpen) return null;

  const handleSelectPreset = (index: number) => {
    setSelectedPresetIndex(index);
    const p = PRESET_PUS[index];
    setAdcVotes(p.defaultVotes.adc);
    setApcVotes(p.defaultVotes.apc);
    setPdpVotes(p.defaultVotes.pdp);
    setLpVotes(p.defaultVotes.lp);
    setNnppVotes(p.defaultVotes.nnpp);
    setRejectedBallots(0);
    setStatusMessage(null);
  };

  const totalValidVotes = adcVotes + apcVotes + pdpVotes + lpVotes + nnppVotes;
  const totalVotesCast = totalValidVotes + rejectedBallots;
  const accreditedVoters = totalVotesCast; // In balanced election, accredited = cast

  const handleTransmitReport = async () => {
    setIsTransmitting(true);
    setStatusMessage(null);

    const payload = {
      pu_id: `pu-${currentPreset.pu_code}-${Date.now()}`,
      pu_code: currentPreset.pu_code,
      pu_name: currentPreset.pu_name,
      registered_voters: currentPreset.registered_voters,
      accredited_voters: accreditedVoters,
      rejected_ballots: rejectedBallots,
      party_votes: {
        ADC: adcVotes,
        APC: apcVotes,
        PDP: pdpVotes,
        LP: lpVotes,
        NNPP: nnppVotes,
      },
      form_ec8a_url: '/sample_ec8a_snap.jpg',
      agent_name: agentName,
      agent_phone: '08031234567',
      bvas_zero_accredited_verified: true,
      agent_signature_confirmed: true,
      over_voting_detected: false,
    };

    try {
      const res = await fetch('/api/results', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to submit PU result');

      setStatusMessage({
        type: 'success',
        text: `⚡ Form EC8A Successfully Transmitted! PU [${currentPreset.pu_code}] in ${currentPreset.state_name} (${currentPreset.zone}) is now collated. ADC gained +${adcVotes.toLocaleString()} votes.`,
      });

      if (typeof window !== 'undefined' && 'BroadcastChannel' in window) {
        try {
          const channel = new BroadcastChannel('election_situation_room_stream');
          channel.postMessage({ type: 'NEW_PU_RESULT', result: data.result || payload });
          channel.close();
        } catch (_) {}
      }

      // Multi-device real-time sync across phones, tablets and laptops
      try {
        fetch('https://ntfy.sh/atiku2027_situation_room_live_pu_feed', {
          method: 'POST',
          headers: { 'Title': 'NEW_PU_RESULT', 'Priority': 'high' },
          body: JSON.stringify({ type: 'NEW_PU_RESULT', result: data.result || payload }),
        }).catch(() => {});
      } catch (_) {}

      if (data.result) {
        onTransmissionComplete(data.result);
      }
    } catch (err: any) {
      setStatusMessage({
        type: 'error',
        text: err.message || 'Error transmitting PU result.',
      });
    } finally {
      setIsTransmitting(false);
    }
  };

  const handleResetTransmissions = async () => {
    setIsTransmitting(true);
    setStatusMessage(null);
    try {
      const res = await fetch('/api/results', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'reset' }),
      });
      const data = await res.json();
      if (res.ok) {
        if (typeof window !== 'undefined' && 'BroadcastChannel' in window) {
          try {
            const channel = new BroadcastChannel('election_situation_room_stream');
            channel.postMessage({ type: 'RESET_PU_RESULTS' });
            channel.close();
          } catch (_) {}
        }

        try {
          fetch('https://ntfy.sh/atiku2027_situation_room_live_pu_feed', {
            method: 'POST',
            headers: { 'Title': 'RESET_PU_RESULTS', 'Priority': 'high' },
            body: JSON.stringify({ type: 'RESET_PU_RESULTS' }),
          }).catch(() => {});
        } catch (_) {}

        setStatusMessage({
          type: 'success',
          text: '🔄 All simulated PU transmissions cleared. Situation Room returned to pristine zero baseline.',
        });
        onResetComplete();
      }
    } catch (err: any) {
      setStatusMessage({
        type: 'error',
        text: 'Error resetting data: ' + err.message,
      });
    } finally {
      setIsTransmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-5 bg-slate-950/80 backdrop-blur-sm overflow-y-auto">
      <div className="bg-[#0B132B] text-white rounded-2xl border border-slate-700 shadow-2xl max-w-2xl w-full overflow-hidden my-auto animate-in fade-in zoom-in-95 duration-150">
        {/* Header */}
        <div className="p-4 sm:p-5 border-b border-slate-800 flex items-center justify-between bg-gradient-to-r from-emerald-950/70 via-slate-900 to-purple-950/70">
          <div className="flex items-center gap-3">
            <div className="p-2.5 rounded-xl bg-emerald-600 text-white shadow-md">
              <Zap className="w-5 h-5" />
            </div>
            <div>
              <h3 className="text-base font-black text-white flex items-center gap-2">
                Live Polling Unit Agent Transmission Simulator
                <span className="text-[10px] px-2 py-0.5 rounded-full bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-mono font-bold">
                  e-EC8A Test
                </span>
              </h3>
              <p className="text-xs text-slate-300">
                Simulate an accredited field agent uploading a signed Form EC8A report to watch votes reflect live across the Situation Room.
              </p>
            </div>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800 transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Body Content */}
        <div className="p-4 sm:p-5 space-y-4 max-h-[75vh] overflow-y-auto">
          {/* Status Message Banner */}
          {statusMessage && (
            <div
              className={`p-3 rounded-xl border flex items-start gap-2.5 text-xs font-semibold ${
                statusMessage.type === 'success'
                  ? 'bg-emerald-950/80 border-emerald-500 text-emerald-200'
                  : 'bg-rose-950/80 border-rose-500 text-rose-200'
              }`}
            >
              {statusMessage.type === 'success' ? (
                <CheckCircle2 className="w-4 h-4 text-emerald-400 shrink-0 mt-0.5" />
              ) : (
                <AlertTriangle className="w-4 h-4 text-rose-400 shrink-0 mt-0.5" />
              )}
              <div className="flex-1">{statusMessage.text}</div>
            </div>
          )}

          {/* 1. Step A: Choose Sample Polling Unit */}
          <div>
            <label className="text-xs font-black text-slate-300 uppercase tracking-wider block mb-2">
              1. Select Polling Unit to Transmit From:
            </label>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
              {PRESET_PUS.map((p, idx) => (
                <button
                  key={p.pu_code}
                  type="button"
                  onClick={() => handleSelectPreset(idx)}
                  className={`p-2.5 rounded-xl border text-left transition flex flex-col justify-between ${
                    selectedPresetIndex === idx
                      ? 'bg-emerald-950/90 border-emerald-500 shadow-md ring-1 ring-emerald-400'
                      : 'bg-slate-900 border-slate-800 text-slate-300 hover:border-slate-700'
                  }`}
                >
                  <div className="text-[10px] font-bold text-emerald-400 uppercase tracking-tight">
                    {p.zone.split(' ')[0]} &bull; {p.state_name}
                  </div>
                  <div className="text-xs font-black text-white truncate mt-0.5">
                    {p.lga_name}
                  </div>
                  <div className="text-[10px] font-mono text-slate-400 mt-1 truncate">
                    PU {p.pu_code}
                  </div>
                </button>
              ))}
            </div>
          </div>

          {/* 2. Step B: Unit Information Card */}
          <div className="bg-slate-900/90 rounded-xl border border-slate-800 p-3.5 space-y-2 text-xs">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-1 border-b border-slate-800 pb-2">
              <div>
                <span className="font-black text-white text-sm">{currentPreset.pu_name}</span>
                <span className="text-slate-400 text-[11px] block">
                  {currentPreset.ward_name} Ward &bull; {currentPreset.lga_name} LGA &bull; {currentPreset.state_name} State ({currentPreset.zone})
                </span>
              </div>
              <div className="flex items-center gap-2">
                <span className="px-2 py-0.5 rounded-md bg-purple-950 border border-purple-800 text-purple-300 font-mono text-[10px] font-bold">
                  PU Code: {currentPreset.pu_code}
                </span>
                <span className="px-2 py-0.5 rounded-md bg-emerald-950 border border-emerald-800 text-emerald-300 font-mono text-[10px] font-bold">
                  {currentPreset.registered_voters.toLocaleString()} Voters 🔒
                </span>
              </div>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-1">
              <div>
                <label className="text-[10px] font-bold text-slate-400 block mb-1">
                  Accredited Field Agent Name:
                </label>
                <input
                  type="text"
                  value={agentName}
                  onChange={(e) => setAgentName(e.target.value)}
                  className="w-full bg-slate-950 border border-slate-700 rounded-lg px-2.5 py-1.5 text-xs text-white focus:outline-none focus:border-emerald-500 font-medium"
                />
              </div>
              <div>
                <label className="text-[10px] font-bold text-slate-400 block mb-1">
                  Accreditation &amp; BVAS Status:
                </label>
                <div className="flex items-center gap-2 text-[11px] text-emerald-300 bg-slate-950/80 p-1.5 rounded-lg border border-slate-800">
                  <ShieldCheck className="w-4 h-4 text-emerald-400 shrink-0" />
                  <span>BVAS 0-Audit Verified &bull; Section 47 Validated</span>
                </div>
              </div>
            </div>
          </div>

          {/* 3. Step C: Enter Candidate & Party Vote Tallies */}
          <div>
            <label className="text-xs font-black text-slate-300 uppercase tracking-wider block mb-2">
              2. Form EC8A Party Vote Tallies:
            </label>
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-2.5">
              {/* ADC */}
              <div className="bg-purple-950/40 border border-purple-800/80 rounded-xl p-2.5">
                <div className="flex items-center justify-between mb-1">
                  <span className="text-[11px] font-black text-purple-300">ADC (Atiku)</span>
                  <span className="text-[9px] bg-purple-900/80 text-purple-200 px-1.5 py-0.2 rounded font-bold">
                    Primary
                  </span>
                </div>
                <input
                  type="number"
                  min="0"
                  value={adcVotes}
                  onChange={(e) => setAdcVotes(Math.max(0, parseInt(e.target.value || '0', 10)))}
                  className="w-full bg-slate-950 border border-purple-600 rounded-lg px-2.5 py-1.5 text-base font-black text-purple-200 font-mono focus:outline-none focus:ring-1 focus:ring-purple-400"
                />
              </div>

              {/* APC */}
              <div className="bg-emerald-950/40 border border-emerald-800/80 rounded-xl p-2.5">
                <span className="text-[11px] font-black text-emerald-300 block mb-1">APC (Tinubu)</span>
                <input
                  type="number"
                  min="0"
                  value={apcVotes}
                  onChange={(e) => setApcVotes(Math.max(0, parseInt(e.target.value || '0', 10)))}
                  className="w-full bg-slate-950 border border-emerald-600 rounded-lg px-2.5 py-1.5 text-base font-black text-emerald-200 font-mono focus:outline-none focus:ring-1 focus:ring-emerald-400"
                />
              </div>

              {/* PDP */}
              <div className="bg-rose-950/40 border border-rose-800/80 rounded-xl p-2.5">
                <span className="text-[11px] font-black text-rose-300 block mb-1">PDP</span>
                <input
                  type="number"
                  min="0"
                  value={pdpVotes}
                  onChange={(e) => setPdpVotes(Math.max(0, parseInt(e.target.value || '0', 10)))}
                  className="w-full bg-slate-950 border border-rose-600 rounded-lg px-2.5 py-1.5 text-base font-black text-rose-200 font-mono focus:outline-none focus:ring-1 focus:ring-rose-400"
                />
              </div>

              {/* LP */}
              <div className="bg-orange-950/40 border border-orange-800/80 rounded-xl p-2.5">
                <span className="text-[11px] font-black text-orange-300 block mb-1">LP (Peter Obi)</span>
                <input
                  type="number"
                  min="0"
                  value={lpVotes}
                  onChange={(e) => setLpVotes(Math.max(0, parseInt(e.target.value || '0', 10)))}
                  className="w-full bg-slate-950 border border-orange-600 rounded-lg px-2.5 py-1.5 text-base font-black text-orange-200 font-mono focus:outline-none focus:ring-1 focus:ring-orange-400"
                />
              </div>

              {/* NNPP */}
              <div className="bg-blue-950/40 border border-blue-800/80 rounded-xl p-2.5">
                <span className="text-[11px] font-black text-blue-300 block mb-1">NNPP (Kwankwaso)</span>
                <input
                  type="number"
                  min="0"
                  value={nnppVotes}
                  onChange={(e) => setNnppVotes(Math.max(0, parseInt(e.target.value || '0', 10)))}
                  className="w-full bg-slate-950 border border-blue-600 rounded-lg px-2.5 py-1.5 text-base font-black text-blue-200 font-mono focus:outline-none focus:ring-1 focus:ring-blue-400"
                />
              </div>

              {/* Rejected Ballots */}
              <div className="bg-slate-900 border border-slate-700 rounded-xl p-2.5">
                <span className="text-[11px] font-bold text-slate-300 block mb-1">Rejected Ballots</span>
                <input
                  type="number"
                  min="0"
                  value={rejectedBallots}
                  onChange={(e) => setRejectedBallots(Math.max(0, parseInt(e.target.value || '0', 10)))}
                  className="w-full bg-slate-950 border border-slate-700 rounded-lg px-2.5 py-1.5 text-base font-black text-slate-300 font-mono focus:outline-none focus:border-slate-500"
                />
              </div>
            </div>
          </div>

          {/* 4. Statutory Validation Summary */}
          <div className="p-3 rounded-xl bg-slate-900 border border-slate-800 flex items-center justify-between text-xs font-mono">
            <div>
              <span className="text-slate-400">Total Valid Votes: </span>
              <strong className="text-white">{totalValidVotes.toLocaleString()}</strong>
              <span className="text-slate-400 ml-2">Total Cast: </span>
              <strong className="text-white">{totalVotesCast.toLocaleString()}</strong>
            </div>
            <div className="flex items-center gap-1.5 text-emerald-400 font-bold">
              <Check className="w-4 h-4" />
              <span>Balanced (Accredited = {accreditedVoters.toLocaleString()})</span>
            </div>
          </div>
        </div>

        {/* Footer Actions */}
        <div className="p-4 sm:p-5 border-t border-slate-800 bg-slate-900/60 flex flex-col sm:flex-row items-center justify-between gap-3">
          <div className="text-xs text-slate-400 flex items-center gap-2">
            <span>Currently Collated:</span>
            <span className="px-2 py-0.5 rounded-full bg-slate-800 text-emerald-400 font-bold font-mono">
              {totalCurrentlySubmitted} PU{totalCurrentlySubmitted === 1 ? '' : 's'}
            </span>
          </div>

          <div className="flex items-center gap-2 w-full sm:w-auto">
            {totalCurrentlySubmitted > 0 && (
              <button
                type="button"
                onClick={handleResetTransmissions}
                disabled={isTransmitting}
                className="px-3 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white border border-slate-700 text-xs font-bold transition flex items-center gap-1.5 disabled:opacity-50"
              >
                <RotateCcw className="w-3.5 h-3.5" />
                <span>Reset (0 Baseline)</span>
              </button>
            )}

            <button
              type="button"
              onClick={handleTransmitReport}
              disabled={isTransmitting || totalValidVotes === 0}
              className="flex-1 sm:flex-none px-4 py-2 rounded-xl bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-500 hover:to-teal-500 text-slate-950 font-black text-xs transition shadow-lg flex items-center justify-center gap-2 disabled:opacity-50"
            >
              <Send className="w-4 h-4" />
              <span>{isTransmitting ? 'Transmitting...' : 'Transmit Form EC8A to Situation Room'}</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
