'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import {
  NATIONAL_SITUATION_METRICS,
  LIVE_STATES_COLLATION,
  StateCollationStatus
} from '@/lib/liveCollationData';
import { NationalCommunicationDesk } from '@/components/communication/NationalCommunicationDesk';
import {
  Vote,
  Radio,
  FileCheck,
  AlertTriangle,
  Users,
  Search,
  Maximize2,
  TrendingUp,
  ShieldCheck,
  Sparkles,
  Layers,
  ChevronRight,
  MapPin,
  Clock,
  MessageSquare,
  KeyRound,
  Award
} from 'lucide-react';
import { AppUser } from '@/types/auth';
import { HierarchicalSubordinatesDesk } from './HierarchicalSubordinatesDesk';

export const SituationRoomDashboard: React.FC<{ currentUser: AppUser }> = ({ currentUser }) => {
  const [selectedZone, setSelectedZone] = useState<string>('ALL');
  const [searchQuery, setSearchQuery] = useState<string>('');
  const [isBigScreenMode, setIsBigScreenMode] = useState<boolean>(false);

  const zones = ['ALL', 'North West', 'North East', 'North Central', 'South West', 'South South', 'South East'];

  const filteredStates = LIVE_STATES_COLLATION.filter((s) => {
    const matchesZone = selectedZone === 'ALL' || s.zone === selectedZone;
    const matchesSearch =
      s.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      s.code.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesZone && matchesSearch;
  });

  return (
    <div className={`space-y-8 ${isBigScreenMode ? 'fixed inset-0 z-50 bg-[#050B14] p-6 overflow-y-auto' : ''}`}>
      {/* Big Screen Bar / Exit */}
      {isBigScreenMode && (
        <div className="flex items-center justify-between bg-[#0A1424] p-3 rounded-xl border border-slate-800 mb-4">
          <div className="flex items-center space-x-2 text-rose-400 font-bold text-xs uppercase">
            <Radio className="w-4 h-4 animate-ping" />
            <span>SITUATION ROOM EXECUTIVE PROJECTOR MODE ACTIVE</span>
          </div>
          <button
            onClick={() => setIsBigScreenMode(false)}
            className="px-3 py-1 rounded bg-slate-800 text-slate-200 text-xs font-semibold hover:bg-slate-700"
          >
            Exit Big Screen
          </button>
        </div>
      )}

      {/* PRESIDENTIAL COMMAND BRIEFING BANNER WITH ATIKU PHOTO */}
      <div className="relative overflow-hidden rounded-3xl bg-gradient-to-r from-[#07152B] via-[#0A1D3A] to-[#050D1B] border border-amber-400/50 p-6 sm:p-8 shadow-2xl">
        <div className="absolute top-0 right-0 w-96 h-96 bg-amber-400/10 rounded-full blur-3xl pointer-events-none" />
        <div className="absolute bottom-0 left-1/3 w-64 h-64 bg-sky-500/10 rounded-full blur-3xl pointer-events-none" />

        <div className="relative z-10 flex flex-col md:flex-row items-center justify-between gap-6">
          <div className="flex flex-col sm:flex-row items-center sm:items-start text-center sm:text-left gap-5">
            {/* Atiku Portrait with Gold Presidential Ring */}
            <div className="relative flex-shrink-0">
              <div className="w-24 h-24 sm:w-28 sm:h-28 rounded-2xl overflow-hidden border-2 border-amber-400 shadow-xl shadow-amber-500/20 bg-slate-900">
                <img
                  src="/atiku-portrait.jpg"
                  alt="Alhaji Atiku Abubakar"
                  className="w-full h-full object-cover"
                />
              </div>
              <div className="absolute -bottom-2 -right-2 bg-amber-400 text-slate-950 font-black text-[9px] px-2 py-0.5 rounded-full border border-slate-900 shadow">
                WAZIRI 2027
              </div>
            </div>

            <div className="space-y-1.5">
              <div className="flex flex-wrap items-center justify-center sm:justify-start gap-2">
                <span className="px-2.5 py-0.5 rounded-md bg-amber-400/20 text-amber-300 border border-amber-400/40 text-xs font-black tracking-wider uppercase">
                  National Situation Room
                </span>
                <span className="px-2.5 py-0.5 rounded-md bg-sky-500/20 text-sky-300 border border-sky-500/40 text-xs font-black tracking-wider uppercase">
                  African Democratic Congress (ADC)
                </span>
                <span className="px-2 py-0.5 rounded-full bg-slate-800 text-slate-300 text-[10px] font-mono">
                  PVT Parallel Vote Tabulation
                </span>
              </div>
              <h1 className="text-2xl sm:text-3xl font-black text-white tracking-tight">
                Atiku Abubakar Presidential Command Briefing
              </h1>
              <p className="text-xs sm:text-sm text-slate-300 max-w-2xl leading-relaxed">
                Live parallel tallying across 176,846 Polling Units with dual-channel physical Form EC8A vs. INEC IReV forensic reconciliation.
              </p>
            </div>
          </div>

          {/* Presidential Collation Indicators */}
          <div className="flex-shrink-0 flex items-center gap-3 bg-slate-950/70 p-4 rounded-2xl border border-slate-800 backdrop-blur-sm">
            <div className="text-right">
              <span className="text-[10px] text-slate-400 uppercase font-bold block">Current Electoral Lead</span>
              <span className="text-xl font-black text-amber-400">LEADING IN {NATIONAL_SITUATION_METRICS.atiku_adc.statesLeading} STATES</span>
              <span className="text-[10px] text-emerald-400 block font-mono">{NATIONAL_SITUATION_METRICS.atiku_adc.statesMet25} States Met 25% Threshold</span>
            </div>
            <div className="w-12 h-12 rounded-xl bg-amber-400/20 border border-amber-400/40 flex items-center justify-center text-amber-300">
              <Award className="w-6 h-6" />
            </div>
          </div>
        </div>

        {/* Rapid Status Bar */}
        <div className="mt-6 pt-6 border-t border-slate-800/80 grid grid-cols-2 sm:grid-cols-4 gap-4 text-xs">
          <div>
            <span className="text-slate-400 block text-[11px]">PVT Confidence Score:</span>
            <span className="font-mono font-bold text-white text-sm">
              {NATIONAL_SITUATION_METRICS.pvtConfidenceScore}%
            </span>
          </div>
          <div>
            <span className="text-slate-400 block text-[11px]">Accredited Voters:</span>
            <span className="font-mono font-bold text-emerald-400 text-sm">
              {NATIONAL_SITUATION_METRICS.totalAccreditedVoters.toLocaleString()}
            </span>
          </div>
          <div>
            <span className="text-slate-400 block text-[11px]">National Rejection Rate:</span>
            <span className="font-mono font-bold text-amber-400 text-sm">
              {NATIONAL_SITUATION_METRICS.nationalRejectionRate}% (Suppressed from 3.76%)
            </span>
          </div>
          <div>
            <span className="text-slate-400 block text-[11px]">Total Rejected Ballots:</span>
            <span className="font-mono font-bold text-rose-400 text-sm">
              {NATIONAL_SITUATION_METRICS.totalRejectedVotes.toLocaleString()}
            </span>
          </div>
        </div>
      </div>

      {/* HIERARCHICAL SUBORDINATE DESK (Situation Room commands all 36 State Leads) */}
      <HierarchicalSubordinatesDesk currentUser={currentUser} />

      {/* TOP SUMMARY KPI TILES */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
        <div className="bg-[#0A1424] border border-slate-800 p-4 rounded-xl space-y-1">
          <div className="flex items-center justify-between text-slate-400 text-xs font-semibold">
            <span>Reported PUs</span>
            <Vote className="w-4 h-4 text-sky-400" />
          </div>
          <div className="text-xl font-black text-white">
            {NATIONAL_SITUATION_METRICS.reportedPollingUnits.toLocaleString()}
          </div>
          <div className="text-[10px] text-slate-400">
            {NATIONAL_SITUATION_METRICS.reportingPercentage}% of 176,846 PUs
          </div>
        </div>

        <div className="bg-[#0A1424] border border-amber-500/30 p-4 rounded-xl space-y-1">
          <div className="flex items-center justify-between text-amber-300 text-xs font-semibold">
            <span>Atiku (ADC)</span>
            <TrendingUp className="w-4 h-4 text-amber-400" />
          </div>
          <div className="text-xl font-black text-amber-400">
            {NATIONAL_SITUATION_METRICS.atiku_adc.votes.toLocaleString()}
          </div>
          <div className="text-[10px] text-emerald-400 font-semibold">
            {NATIONAL_SITUATION_METRICS.atiku_adc.percentage}% (Leading 18 States)
          </div>
        </div>

        <div className="bg-[#0A1424] border border-slate-800 p-4 rounded-xl space-y-1">
          <div className="flex items-center justify-between text-slate-400 text-xs font-semibold">
            <span>Tinubu (APC)</span>
            <span className="text-[10px] text-slate-500">Trailing</span>
          </div>
          <div className="text-xl font-black text-slate-200">
            {NATIONAL_SITUATION_METRICS.tinubu_apc.votes.toLocaleString()}
          </div>
          <div className="text-[10px] text-slate-400">
            {NATIONAL_SITUATION_METRICS.tinubu_apc.percentage}% (11 States)
          </div>
        </div>

        <div className="bg-[#0A1424] border border-slate-800 p-4 rounded-xl space-y-1">
          <div className="flex items-center justify-between text-slate-400 text-xs font-semibold">
            <span>Obi / LP</span>
            <span className="text-[10px] text-slate-500">Trailing</span>
          </div>
          <div className="text-xl font-black text-slate-200">
            {NATIONAL_SITUATION_METRICS.obi_lp.votes.toLocaleString()}
          </div>
          <div className="text-[10px] text-slate-400">
            {NATIONAL_SITUATION_METRICS.obi_lp.percentage}% (7 States + FCT)
          </div>
        </div>

        <div className="bg-[#0A1424] border border-emerald-500/30 p-4 rounded-xl space-y-1">
          <div className="flex items-center justify-between text-emerald-300 text-xs font-semibold">
            <span>Kwankwaso (NNPP)</span>
            <FileCheck className="w-4 h-4 text-emerald-400" />
          </div>
          <div className="text-xl font-black text-emerald-400">
            {NATIONAL_SITUATION_METRICS.kwankwaso_nnpp.votes.toLocaleString()}
          </div>
          <div className="text-[10px] text-slate-400">
            {NATIONAL_SITUATION_METRICS.kwankwaso_nnpp.percentage}% (1 State)
          </div>
        </div>

        <div className="bg-[#0A1424] border border-rose-500/30 p-4 rounded-xl space-y-1">
          <div className="flex items-center justify-between text-rose-300 text-xs font-semibold">
            <span>Rejected Ballots</span>
            <AlertTriangle className="w-4 h-4 text-rose-400" />
          </div>
          <div className="text-xl font-black text-rose-400">
            {NATIONAL_SITUATION_METRICS.totalRejectedVotes.toLocaleString()}
          </div>
          <div className="text-[10px] text-emerald-400 font-semibold">
            {NATIONAL_SITUATION_METRICS.nationalRejectionRate}% Invalidation Rate
          </div>
        </div>
      </div>

      {/* NATIONAL MULTI-TIER COMMUNICATION DESK */}
      <NationalCommunicationDesk />

      {/* 36 STATES COLLATION MONITOR */}
      <div className="bg-[#0A1424] border border-slate-800 rounded-2xl p-6 space-y-5">
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 border-b border-slate-800 pb-4">
          <div>
            <h3 className="text-base font-black text-white">
              State-by-State Collation Feed (36 States + FCT)
            </h3>
            <p className="text-xs text-slate-400">
              Live updates from ADC State Supervisors and LGA Collation Centers.
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-2">
            <div className="relative">
              <Search className="w-3.5 h-3.5 text-slate-500 absolute left-3 top-2.5" />
              <input
                type="text"
                placeholder="Search state..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-8 pr-3 py-1.5 bg-slate-900 border border-slate-700 rounded-lg text-xs text-white placeholder-slate-500 focus:outline-none focus:border-sky-500"
              />
            </div>

            <div className="flex overflow-x-auto space-x-1 max-w-full text-xs">
              {zones.map((zone) => (
                <button
                  key={zone}
                  onClick={() => setSelectedZone(zone)}
                  className={`px-2.5 py-1 rounded-md text-[11px] font-semibold transition-all whitespace-nowrap ${
                    selectedZone === zone
                      ? 'bg-sky-600 text-white'
                      : 'bg-slate-900 text-slate-400 hover:text-white'
                  }`}
                >
                  {zone}
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* States Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredStates.map((state) => {
            const isLeadingADC = state.leadingParty === 'ADC';
            return (
              <div
                key={state.code}
                className={`p-4 rounded-xl border transition-all ${
                  isLeadingADC
                    ? 'bg-gradient-to-br from-[#0B1A2E] to-[#0A1424] border-sky-500/40 hover:border-sky-400'
                    : 'bg-[#0A1424] border-slate-800 hover:border-slate-700'
                }`}
              >
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center space-x-2">
                    <span className="font-black text-sm text-white">{state.name}</span>
                    <span className="text-[10px] font-mono px-1.5 py-0.2 rounded bg-slate-800 text-slate-400">
                      {state.code}
                    </span>
                  </div>
                  <span
                    className={`text-[10px] font-black uppercase px-2 py-0.5 rounded-full ${
                      isLeadingADC
                        ? 'bg-amber-400/20 text-amber-300 border border-amber-400/40'
                        : 'bg-slate-800 text-slate-300'
                    }`}
                  >
                    {isLeadingADC ? 'ADC Leading' : `${state.leadingParty} Leading`}
                  </span>
                </div>

                <div className="space-y-1.5 text-xs">
                  <div className="flex justify-between text-slate-400">
                    <span>Reporting PUs:</span>
                    <span className="font-mono text-slate-200">
                      {state.reportedPUs.toLocaleString()} / {state.totalPUs.toLocaleString()} ({state.reportingPercentage}%)
                    </span>
                  </div>

                  <div className="w-full bg-slate-900 h-1.5 rounded-full overflow-hidden">
                    <div
                      className="bg-sky-500 h-full rounded-full transition-all"
                      style={{ width: `${state.reportingPercentage}%` }}
                    />
                  </div>

                  <div className="pt-2 grid grid-cols-3 gap-1 text-[11px] font-mono">
                    <div className="bg-slate-900/80 p-1.5 rounded text-center">
                      <span className="text-slate-400 block text-[9px]">ADC</span>
                      <span className="text-amber-400 font-bold">{state.votes.adc.toLocaleString()}</span>
                    </div>
                    <div className="bg-slate-900/80 p-1.5 rounded text-center">
                      <span className="text-slate-400 block text-[9px]">APC</span>
                      <span className="text-slate-300 font-bold">{state.votes.apc.toLocaleString()}</span>
                    </div>
                    <div className="bg-slate-900/80 p-1.5 rounded text-center">
                      <span className="text-slate-400 block text-[9px]">LP</span>
                      <span className="text-slate-300 font-bold">{state.votes.lp.toLocaleString()}</span>
                    </div>
                  </div>

                  <div className="pt-2 flex items-center justify-between text-[11px] text-slate-400">
                    <span>Rejected Ballots:</span>
                    <span className="text-rose-400 font-bold">
                      {state.rejectedVotes.toLocaleString()} ({state.rejectionRate}%)
                    </span>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};
