'use client';

import React, { useState } from 'react';
import {
  X,
  User,
  Phone,
  Clock,
  CheckCircle2,
  AlertTriangle,
  ZoomIn,
  ZoomOut,
  RotateCw,
  Maximize2,
  ShieldCheck,
  ShieldAlert,
  FileSpreadsheet,
  Cpu,
  Layers,
  MapPin,
  ExternalLink,
  Scale,
  Download,
  FileCheck
} from 'lucide-react';
import { PollingUnitItem, PuResultData } from '@/types';
import { POLITICAL_PARTIES } from '@/lib/electoralData';

interface Props {
  isOpen: boolean;
  onClose: () => void;
  pu: PollingUnitItem | null;
  result: PuResultData | null;
  stateName?: string;
  lgaName?: string;
  wardName?: string;
}

export const PuDetailModal: React.FC<Props> = ({
  isOpen,
  onClose,
  pu,
  result,
  stateName = 'Lagos',
  lgaName = 'Ikeja',
  wardName = 'Alausa',
}) => {
  const [activeTab, setActiveTab] = useState<'SIDE_BY_SIDE' | 'AGENT_EC8A' | 'INEC_IREV'>('SIDE_BY_SIDE');
  const [zoomLevel, setZoomLevel] = useState<number>(1);
  const [rotation, setRotation] = useState<number>(0);
  const [tribunalFlagged, setTribunalFlagged] = useState<boolean>(false);

  if (!isOpen || !pu) return null;

  // Active result or fallback demo result
  const activeResult: PuResultData = result || {
    pu_id: pu.id,
    pu_code: pu.pu_code,
    registered_voters: pu.registered_voters,
    accredited_voters: 465,
    rejected_ballots: 5,
    party_votes: { ADC: 245, APC: 155, LP: 53, PDP: 7, NNPP: 5, SDP: 0 },
    total_valid_votes: 460,
    total_votes_cast: 465,
    form_ec8a_url: '/sample_ec8a_snap.jpg',
    is_balanced: true,
    discrepancy_count: 0,
    over_voting_detected: false,
    bvas_zero_accredited_verified: true,
    agent_signature_confirmed: true,
    agent_signed_at: '2027-02-27T16:40:00Z',
    status: 'VERIFIED',
    reported_by: 'agent-default',
    submitted_at: '2027-02-27T16:45:00Z',
    agent_name: 'Ibrahim Danjuma (ADC Polling Agent)',
    agent_phone: '08031112222',

    // INEC IReV Server Comparison
    inec_irev_url: '/sample_ec8a_snap.jpg',
    inec_irev_votes: { ADC: 245, APC: 155, LP: 53, PDP: 7, NNPP: 5, SDP: 0 },
    inec_irev_uploaded_at: '2027-02-27T17:05:00Z',
    irev_discrepancy_detected: false,
    irev_variance_notes: '100% IDENTICAL: ADC Agent signed EC8A perfectly matches official INEC IReV portal data.',
  };

  const irevVotes = activeResult.inec_irev_votes || activeResult.party_votes;
  const officialIrevUrl = `https://inecelectionresults.ng/elections/presidential/state/${pu.state_id}/lga/${pu.lga_id}/ward/${pu.ward_id}/pu/${pu.pu_code}`;

  // Check variance between Agent and INEC IReV
  let totalVariance = 0;
  const partyVariances: Record<string, number> = {};
  POLITICAL_PARTIES.forEach((p) => {
    const agentCount = activeResult.party_votes[p.code] || 0;
    const irevCount = irevVotes[p.code] || 0;
    const diff = agentCount - irevCount;
    partyVariances[p.code] = diff;
    totalVariance += Math.abs(diff);
  });

  const isIrevMatched = totalVariance === 0 && !activeResult.irev_discrepancy_detected;

  const handleZoomIn = () => setZoomLevel((prev) => Math.min(3, prev + 0.25));
  const handleZoomOut = () => setZoomLevel((prev) => Math.max(0.75, prev - 0.25));
  const handleRotate = () => setRotation((prev) => (prev + 90) % 360);
  const handleResetZoom = () => {
    setZoomLevel(1);
    setRotation(0);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-5 bg-black/90 backdrop-blur-md animate-in fade-in overflow-y-auto">
      <div className="w-full max-w-6xl bg-slate-900 border border-purple-900/60 rounded-2xl shadow-2xl overflow-hidden my-auto max-h-[94vh] flex flex-col">
        {/* Header */}
        <div className="p-4 sm:p-5 bg-slate-950 border-b border-purple-900/50 flex items-center justify-between flex-shrink-0">
          <div>
            <div className="flex items-center gap-2">
              <span className="text-xs px-2.5 py-0.5 rounded-md bg-purple-950 text-amber-300 font-mono font-bold border border-purple-700">
                {pu.pu_code}
              </span>
              <h3 className="text-base sm:text-lg font-black text-white">
                {pu.pu_name}
              </h3>
            </div>
            <p className="text-xs text-slate-400 flex items-center gap-1 mt-1">
              <MapPin className="w-3.5 h-3.5 text-amber-400" />
              {stateName} State &bull; {lgaName} LGA &bull; {wardName} Ward &bull; {pu.delimitation_address || 'INEC Delimited Polling Station'}
            </p>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-xl text-slate-400 hover:text-white hover:bg-slate-800 transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Navigation Tabs: Side-by-Side Comparison vs Views */}
        <div className="flex items-center justify-between px-5 pt-3 bg-slate-950/80 border-b border-slate-800 flex-shrink-0">
          <div className="flex space-x-2">
            <button
              onClick={() => setActiveTab('SIDE_BY_SIDE')}
              className={`py-2 px-3 text-xs font-bold rounded-t-lg transition border-b-2 flex items-center gap-1.5 ${
                activeTab === 'SIDE_BY_SIDE'
                  ? 'border-purple-500 text-amber-300 bg-slate-900'
                  : 'border-transparent text-slate-400 hover:text-white'
              }`}
            >
              <Scale className="w-4 h-4 text-purple-400" />
              Side-by-Side: ADC Agent EC8A vs INEC IReV Server
            </button>
            <button
              onClick={() => setActiveTab('AGENT_EC8A')}
              className={`py-2 px-3 text-xs font-bold rounded-t-lg transition border-b-2 flex items-center gap-1.5 ${
                activeTab === 'AGENT_EC8A'
                  ? 'border-purple-500 text-purple-300 bg-slate-900'
                  : 'border-transparent text-slate-400 hover:text-white'
              }`}
            >
              <FileSpreadsheet className="w-4 h-4 text-purple-400" />
              ADC Agent Signed EC8A Full Viewer
            </button>
            <button
              onClick={() => setActiveTab('INEC_IREV')}
              className={`py-2 px-3 text-xs font-bold rounded-t-lg transition border-b-2 flex items-center gap-1.5 ${
                activeTab === 'INEC_IREV'
                  ? 'border-purple-500 text-emerald-300 bg-slate-900'
                  : 'border-transparent text-slate-400 hover:text-white'
              }`}
            >
              <ExternalLink className="w-4 h-4 text-emerald-400" />
              INEC Official IReV Portal Snapshot
            </button>
          </div>

          <div className="hidden sm:flex items-center gap-2">
            <a
              href={officialIrevUrl}
              target="_blank"
              rel="noreferrer"
              className="text-[11px] text-emerald-400 hover:text-emerald-300 font-semibold flex items-center gap-1 bg-emerald-950/60 px-2.5 py-1 rounded-lg border border-emerald-800"
            >
              <span>Direct Link to INEC IReV Server</span>
              <ExternalLink className="w-3 h-3" />
            </a>
          </div>
        </div>

        {/* Modal Body */}
        <div className="flex-1 overflow-y-auto p-4 sm:p-6 space-y-6">
          {/* IREV COMPARISON AUDIT BANNER */}
          <div
            className={`p-4 rounded-xl border flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 shadow-md ${
              isIrevMatched
                ? 'bg-emerald-950/40 border-emerald-500/80 text-emerald-200'
                : 'bg-rose-950/60 border-rose-500 text-rose-200 animate-pulse'
            }`}
          >
            <div className="flex items-center space-x-3">
              {isIrevMatched ? (
                <CheckCircle2 className="w-6 h-6 text-emerald-400 flex-shrink-0" />
              ) : (
                <ShieldAlert className="w-6 h-6 text-rose-400 flex-shrink-0" />
              )}
              <div>
                <div className="text-xs font-black uppercase tracking-wider flex items-center gap-2">
                  <span>
                    {isIrevMatched
                      ? 'INEC IREV COMPARISON: 100% AUDIT MATCH'
                      : 'INEC IREV DISCREPANCY DETECTED!'}
                  </span>
                  <span
                    className={`text-[10px] px-2 py-0.5 rounded font-mono font-bold ${
                      isIrevMatched ? 'bg-emerald-800 text-white' : 'bg-rose-800 text-white'
                    }`}
                  >
                    Variance: {totalVariance} votes
                  </span>
                </div>
                <p className="text-[11px] opacity-90 mt-0.5">
                  {isIrevMatched
                    ? 'Official INEC IReV server data is identical to the verified physical Form EC8A transmitted by our ADC agent.'
                    : 'Discrepancy identified between our agent\'s physical Form EC8A and the upload on inecelectionresults.ng! This PU is tagged for legal tribunal exhibit.'}
                </p>
              </div>
            </div>

            <div className="flex items-center gap-2 self-end sm:self-auto flex-shrink-0">
              <button
                type="button"
                onClick={() => setTribunalFlagged(!tribunalFlagged)}
                className={`px-3 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-1.5 shadow ${
                  tribunalFlagged
                    ? 'bg-amber-500 text-slate-950 font-black'
                    : 'bg-slate-800 hover:bg-slate-700 text-white border border-slate-700'
                }`}
              >
                <Scale className="w-3.5 h-3.5" />
                {tribunalFlagged ? 'Flagged for Tribunal (#EXHIBIT)' : 'Flag for Election Tribunal'}
              </button>
            </div>
          </div>

          {/* TAB 1: SIDE BY SIDE COMPARISON */}
          {activeTab === 'SIDE_BY_SIDE' && (
            <div className="space-y-6">
              {/* Dual Inspection Images */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* Agent Uploaded Form EC8A */}
                <div className="p-4 rounded-xl bg-slate-950 border border-purple-900/40 space-y-2.5">
                  <div className="flex items-center justify-between border-b border-slate-800 pb-2">
                    <span className="text-xs font-bold text-purple-300 uppercase tracking-wider flex items-center gap-1.5">
                      <FileCheck className="w-4 h-4 text-purple-400" />
                      1. ADC Agent Signed Form EC8A
                    </span>
                    <span className="text-[10px] font-mono text-purple-300 bg-purple-950 px-2 py-0.5 rounded border border-purple-800">
                      Transmitted: {new Date(activeResult.submitted_at).toLocaleTimeString()}
                    </span>
                  </div>

                  <div className="h-64 rounded-lg bg-slate-900 overflow-hidden border border-slate-800 flex items-center justify-center relative group">
                    <img
                      src={activeResult.form_ec8a_url}
                      alt="ADC Agent Form EC8A"
                      className="max-h-full object-contain"
                    />
                    <div className="absolute top-2 left-2 bg-black/70 backdrop-blur px-2 py-0.5 rounded text-[10px] text-amber-300 font-mono">
                      Agent: {activeResult.agent_name || 'Ibrahim Danjuma'}
                    </div>
                  </div>

                  <div className="grid grid-cols-3 gap-2 text-center text-xs font-mono pt-1">
                    <div className="p-2 rounded bg-slate-900 border border-slate-800">
                      <span className="block text-[9px] text-slate-400">BVAS 0-Audit</span>
                      <span className="font-bold text-emerald-400">VERIFIED (0)</span>
                    </div>
                    <div className="p-2 rounded bg-slate-900 border border-slate-800">
                      <span className="block text-[9px] text-slate-400">Accredited</span>
                      <span className="font-bold text-white">{activeResult.accredited_voters}</span>
                    </div>
                    <div className="p-2 rounded bg-slate-900 border border-slate-800">
                      <span className="block text-[9px] text-slate-400">ADC Votes</span>
                      <span className="font-bold text-purple-300">{activeResult.party_votes.ADC || 0}</span>
                    </div>
                  </div>
                </div>

                {/* INEC IReV Server Upload */}
                <div className="p-4 rounded-xl bg-slate-950 border border-emerald-900/40 space-y-2.5">
                  <div className="flex items-center justify-between border-b border-slate-800 pb-2">
                    <span className="text-xs font-bold text-emerald-300 uppercase tracking-wider flex items-center gap-1.5">
                      <ExternalLink className="w-4 h-4 text-emerald-400" />
                      2. INEC IReV Server Official Record
                    </span>
                    <span className="text-[10px] font-mono text-emerald-300 bg-emerald-950 px-2 py-0.5 rounded border border-emerald-800">
                      IReV Log: {activeResult.inec_irev_uploaded_at ? new Date(activeResult.inec_irev_uploaded_at).toLocaleTimeString() : '17:05:00'}
                    </span>
                  </div>

                  <div className="h-64 rounded-lg bg-slate-900 overflow-hidden border border-slate-800 flex items-center justify-center relative group">
                    <img
                      src={activeResult.inec_irev_url || activeResult.form_ec8a_url}
                      alt="INEC IReV Portal EC8A"
                      className="max-h-full object-contain"
                    />
                    <div className="absolute top-2 left-2 bg-black/70 backdrop-blur px-2 py-0.5 rounded text-[10px] text-emerald-300 font-mono">
                      Server: inecelectionresults.ng
                    </div>
                  </div>

                  <div className="grid grid-cols-3 gap-2 text-center text-xs font-mono pt-1">
                    <div className="p-2 rounded bg-slate-900 border border-slate-800">
                      <span className="block text-[9px] text-slate-400">IReV Hash</span>
                      <span className="font-bold text-emerald-400">SHA-256 OK</span>
                    </div>
                    <div className="p-2 rounded bg-slate-900 border border-slate-800">
                      <span className="block text-[9px] text-slate-400">Accredited</span>
                      <span className="font-bold text-white">{activeResult.accredited_voters}</span>
                    </div>
                    <div className="p-2 rounded bg-slate-900 border border-slate-800">
                      <span className="block text-[9px] text-slate-400">IReV ADC Votes</span>
                      <span className="font-bold text-emerald-300">{irevVotes.ADC || 0}</span>
                    </div>
                  </div>
                </div>
              </div>

              {/* Side-by-Side Party Vote Variance Table */}
              <div className="p-4 rounded-xl bg-slate-950 border border-slate-800 space-y-3">
                <div className="flex items-center justify-between border-b border-slate-800 pb-2">
                  <span className="text-xs font-bold text-white uppercase tracking-wider flex items-center gap-1.5">
                    <Scale className="w-4 h-4 text-purple-400" />
                    Comparative Party Vote Breakdown & Legal Variance Table
                  </span>
                  <span className="text-[10px] font-mono text-slate-400">
                    Comparing ADC Agent Physical Ballot Tally vs INEC Official Server
                  </span>
                </div>

                <div className="overflow-x-auto">
                  <table className="w-full text-xs text-left border-collapse">
                    <thead>
                      <tr className="border-b border-slate-800 bg-slate-900 text-slate-400 text-[10px] uppercase">
                        <th className="py-2.5 px-3">Political Party</th>
                        <th className="py-2.5 px-3">ADC Field Agent Count</th>
                        <th className="py-2.5 px-3">INEC IReV Server Count</th>
                        <th className="py-2.5 px-3">Audit Delta (&Delta;)</th>
                        <th className="py-2.5 px-3 text-right">Tribunal Evidence Status</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-800/60 font-mono">
                      {POLITICAL_PARTIES.map((party) => {
                        const agentCount = activeResult.party_votes[party.code] || 0;
                        const serverCount = irevVotes[party.code] || 0;
                        const variance = partyVariances[party.code] || 0;
                        const isMatch = variance === 0;

                        return (
                          <tr key={party.code} className="hover:bg-slate-900/50">
                            <td className="py-2.5 px-3 font-bold text-white flex items-center gap-2 font-sans">
                              <span
                                className="w-2.5 h-2.5 rounded-full"
                                style={{ backgroundColor: party.color }}
                              />
                              <span className={party.code === 'ADC' ? 'text-amber-300 font-black' : ''}>
                                {party.code}
                              </span>
                            </td>
                            <td className="py-2.5 px-3 font-bold text-slate-200">
                              {agentCount.toLocaleString()}
                            </td>
                            <td className="py-2.5 px-3 font-bold text-slate-200">
                              {serverCount.toLocaleString()}
                            </td>
                            <td className="py-2.5 px-3">
                              {isMatch ? (
                                <span className="text-emerald-400 font-bold">0 (Matched)</span>
                              ) : (
                                <span className="text-rose-400 font-extrabold">
                                  {variance > 0 ? `+${variance}` : variance} (DISCREPANCY)
                                </span>
                              )}
                            </td>
                            <td className="py-2.5 px-3 text-right">
                              {isMatch ? (
                                <span className="text-[10px] text-emerald-400 bg-emerald-950 px-2 py-0.5 rounded border border-emerald-800">
                                  &check; Corroborated
                                </span>
                              ) : (
                                <span className="text-[10px] text-rose-300 bg-rose-950 px-2 py-0.5 rounded border border-rose-800 font-bold animate-pulse">
                                  &times; Subpoena Target
                                </span>
                              )}
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}

          {/* TAB 2: AGENT FULL ZOOMABLE EC8A VIEWER */}
          {activeTab === 'AGENT_EC8A' && (
            <div className="p-4 rounded-xl bg-slate-950 border border-slate-800 space-y-3">
              <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 border-b border-slate-800/80 pb-2">
                <div>
                  <span className="text-xs font-semibold text-purple-300 uppercase tracking-wider flex items-center gap-1.5">
                    <ShieldCheck className="w-4 h-4 text-emerald-400" />
                    ADC Agent Form EC8A High-Resolution Zoom Inspector
                  </span>
                  <p className="text-[11px] text-slate-400">
                    Physical signed sheet uploaded by agent {activeResult.agent_name}
                  </p>
                </div>

                <div className="flex items-center space-x-1.5 bg-slate-900 p-1 rounded-xl border border-slate-800">
                  <button onClick={handleZoomOut} className="p-1.5 rounded-lg text-slate-400 hover:text-white">
                    <ZoomOut className="w-4 h-4" />
                  </button>
                  <span className="text-xs font-mono px-2 text-slate-300">{Math.round(zoomLevel * 100)}%</span>
                  <button onClick={handleZoomIn} className="p-1.5 rounded-lg text-slate-400 hover:text-white">
                    <ZoomIn className="w-4 h-4" />
                  </button>
                  <button onClick={handleRotate} className="p-1.5 rounded-lg text-slate-400 hover:text-white">
                    <RotateCw className="w-4 h-4" />
                  </button>
                  <button onClick={handleResetZoom} className="text-[10px] font-mono px-2 py-1 rounded bg-slate-800 text-slate-300">
                    Reset
                  </button>
                </div>
              </div>

              <div className="relative w-full h-[450px] bg-slate-950 rounded-xl border border-slate-800 overflow-hidden flex items-center justify-center">
                <div
                  style={{
                    transform: `scale(${zoomLevel}) rotate(${rotation}deg)`,
                    transition: 'transform 0.2s ease-out',
                  }}
                  className="max-w-full max-h-full"
                >
                  <img
                    src={activeResult.form_ec8a_url}
                    alt="Form EC8A Sheet"
                    className="max-h-[420px] object-contain rounded shadow-2xl border border-slate-700"
                  />
                </div>
              </div>
            </div>
          )}

          {/* TAB 3: INEC IREV PORTAL OFFICIAL SNAPSHOT */}
          {activeTab === 'INEC_IREV' && (
            <div className="p-4 rounded-xl bg-slate-950 border border-slate-800 space-y-3">
              <div className="flex items-center justify-between border-b border-slate-800 pb-2">
                <div>
                  <span className="text-xs font-bold text-emerald-400 uppercase tracking-wider flex items-center gap-1.5">
                    <ExternalLink className="w-4 h-4" />
                    INEC Official Results Viewing Portal (IReV) Direct Snapshot
                  </span>
                  <p className="text-[11px] text-slate-400">
                    Synchronized from inecelectionresults.ng server API
                  </p>
                </div>
                <a
                  href={officialIrevUrl}
                  target="_blank"
                  rel="noreferrer"
                  className="px-3 py-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-bold flex items-center gap-1 transition"
                >
                  <span>Open Live inecelectionresults.ng</span>
                  <ExternalLink className="w-3.5 h-3.5" />
                </a>
              </div>

              <div className="p-4 bg-slate-900 rounded-xl border border-slate-800 flex flex-col items-center justify-center text-center space-y-3">
                <div className="w-full max-w-lg h-72 rounded-lg overflow-hidden border border-slate-700 bg-slate-950 flex items-center justify-center">
                  <img
                    src={activeResult.inec_irev_url || activeResult.form_ec8a_url}
                    alt="INEC IReV"
                    className="max-h-full object-contain"
                  />
                </div>
                <div className="text-xs text-slate-300 font-mono">
                  URL: <span className="text-emerald-400">{officialIrevUrl}</span>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Modal Footer with Tribunal Exhibit Summary */}
        <div className="p-4 bg-slate-950 border-t border-purple-900/50 flex flex-col sm:flex-row items-center justify-between gap-3 flex-shrink-0">
          <div className="flex items-center gap-2 text-xs">
            <Scale className="w-4 h-4 text-amber-400" />
            <span className="text-slate-300">
              Tribunal Exhibit Tag:{' '}
              <strong className="text-amber-300 font-mono">
                {tribunalFlagged ? `#ADC-PETITION-EXHIBIT-${pu.pu_code}` : 'Unflagged (Normal Status)'}
              </strong>
            </span>
          </div>

          <div className="flex items-center gap-2 w-full sm:w-auto">
            <button
              onClick={onClose}
              className="flex-1 sm:flex-none py-2 px-5 rounded-xl bg-slate-800 hover:bg-slate-700 text-white text-xs font-bold transition"
            >
              Close Inspector
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};
