'use client';

import React, { useState } from 'react';
import { AppUser, INITIAL_USERS } from '@/types/auth';
import {
  getJurisdictionSummary,
  STATE_VOTERS_REGISTRY,
  KEBBI_LGAS_REGISTRY,
  ARGUNGU_WARDS_REGISTRY,
  WARD_PUS_REGISTRY,
  StateVoterData
} from '@/lib/votersRegistryData';
import { NationalKpiBanners } from './NationalKpiBanners';
import { NigeriaInteractiveSvgMap } from './NigeriaInteractiveSvgMap';
import { StateResultsSummaryTable } from './StateResultsSummaryTable';
import { TurnoutRankingCard } from './TurnoutRankingCard';
import { PartyVotesDonutChart } from './PartyVotesDonutChart';
import { IncidentsTrendCard } from './IncidentsTrendCard';
import { RecentActivityFeed } from './RecentActivityFeed';
import { IssuesAndFlagsCard } from './IssuesAndFlagsCard';
import { MultiTierCommunicationModal } from './MultiTierCommunicationModal';
import { PuEasyAbcdConsole } from '@/components/dashboards/PuEasyAbcdConsole';
import {
  ShieldCheck,
  PhoneCall,
  MessageSquare,
  Sparkles,
  Layers,
  ArrowRight,
  FileCheck2,
  CheckCircle2,
  AlertTriangle,
  ChevronRight,
  Check
} from 'lucide-react';
import Link from 'next/link';

interface HierarchicalExecutiveDashboardProps {
  currentUser?: AppUser;
  onSwitchUser?: (user: AppUser) => void;
  onOpenCommunication?: () => void;
}

export const HierarchicalExecutiveDashboard: React.FC<HierarchicalExecutiveDashboardProps> = ({
  currentUser,
  onSwitchUser
}) => {
  const [selectedState, setSelectedState] = useState<StateVoterData | null>(null);
  const [isCommsModalOpen, setIsCommsModalOpen] = useState(false);
  const [puViewMode, setPuViewMode] = useState<'CONSOLE' | 'OVERVIEW'>('CONSOLE');

  const activeUser = currentUser || INITIAL_USERS[0];

  // Compute dynamically cascading figures based on role (National, State, LGA, Ward, PU)
  const jurisdictionKpis = getJurisdictionSummary(
    activeUser.role,
    activeUser.state,
    activeUser.lga,
    activeUser.ward,
    activeUser.puCode
  );

  return (
    <div className="space-y-6 text-slate-900">
      {/* 1. TOP TIER LEVEL QUICK SWITCHER & NOTIFICATION STRIP */}
      <div className="bg-white rounded-2xl border border-slate-200/90 shadow-xs p-4 sm:p-5 space-y-3.5">
        <div className="flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4">
          <div className="flex items-center space-x-3.5">
            <div className="w-11 h-11 rounded-2xl bg-emerald-600 text-white font-black flex items-center justify-center text-sm shadow-md shadow-emerald-600/20 flex-shrink-0">
              {activeUser.role === 'SITUATION_ROOM'
                ? 'HQ'
                : activeUser.role === 'STATE_SUPERVISOR'
                ? 'ST'
                : activeUser.role === 'LGA_COORDINATOR'
                ? 'LG'
                : activeUser.role === 'WARD_SUPERVISOR'
                ? 'WD'
                : 'PU'}
            </div>
            <div>
              <div className="flex flex-wrap items-center gap-2">
                <span className="px-2.5 py-0.5 rounded-md text-[10px] font-black uppercase bg-emerald-100 text-emerald-800 border border-emerald-200">
                  {activeUser.role.replace(/_/g, ' ')}
                </span>
                <span className="text-base font-black text-slate-900">{jurisdictionKpis.levelName}</span>
                <span className="text-xs text-slate-400 font-mono">Officer: {activeUser.name}</span>
              </div>
              <p className="text-xs text-slate-500 mt-0.5">
                Reflecting real-time voters register ({jurisdictionKpis.registeredVoters.toLocaleString()} voters) & statutory collation cascade down to Ward level.
              </p>
            </div>
          </div>

          {/* Action buttons */}
          <div className="flex flex-wrap items-center gap-2 self-end lg:self-auto">
            <button
              type="button"
              onClick={() => setIsCommsModalOpen(true)}
              className="flex items-center space-x-1.5 px-3.5 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs shadow-sm transition-all"
            >
              <PhoneCall className="w-3.5 h-3.5" />
              <span>Direct Comms Desk</span>
            </button>

            <Link
              href="/ec8a-verifier"
              className="flex items-center space-x-1.5 px-3.5 py-2 rounded-xl bg-slate-900 hover:bg-slate-800 text-white font-bold text-xs shadow-sm transition-all"
            >
              <FileCheck2 className="w-3.5 h-3.5 text-amber-400" />
              <span>e-EC8A Verifier</span>
            </Link>
          </div>
        </div>

        {/* Dynamic 5-Tier Fast Switcher Pills */}
        <div className="pt-3 border-t border-slate-100 flex flex-col sm:flex-row sm:items-center justify-between gap-2.5">
          <div className="flex items-center space-x-2 text-xs font-bold text-slate-500">
            <Layers className="w-3.5 h-3.5 text-emerald-600" />
            <span>Switch Administrative Tier:</span>
          </div>

          <div className="flex flex-wrap items-center gap-1.5">
            {INITIAL_USERS.map((user) => {
              const isCurrent = activeUser.role === user.role;
              const shortLabel =
                user.role === 'SITUATION_ROOM'
                  ? '🇳🇬 National HQ (93.4M)'
                  : user.role === 'STATE_SUPERVISOR'
                  ? '🏛️ Kebbi State (2.03M)'
                  : user.role === 'LGA_COORDINATOR'
                  ? '🏢 Argungu LGA (145K)'
                  : user.role === 'WARD_SUPERVISOR'
                  ? '📍 Argungu Central I (16.8K)'
                  : user.role === 'PU_AGENT'
                  ? '🗳️ PU Sentinel (750)'
                  : user.name;

              return (
                <button
                  key={user.id}
                  type="button"
                  onClick={() => onSwitchUser && onSwitchUser(user)}
                  className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all flex items-center space-x-1.5 ${
                    isCurrent
                      ? 'bg-slate-900 text-white shadow-sm ring-2 ring-emerald-500'
                      : 'bg-slate-100 hover:bg-slate-200 text-slate-700'
                  }`}
                >
                  <span>{shortLabel}</span>
                  {isCurrent && <Check className="w-3 h-3 text-emerald-400" />}
                </button>
              );
            })}
          </div>
        </div>
      </div>

      {/* SPECIAL PU AGENT INTERFACE: EASY AS A-B-C-D CONSOLE */}
      {activeUser.role === 'PU_AGENT' && (
        <div className="space-y-4">
          <div className="flex items-center justify-between px-1">
            <div className="flex items-center space-x-2">
              <span className="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse" />
              <h2 className="text-sm font-black uppercase tracking-wide text-slate-800">
                Polling Unit Sentinel Direct Operations
              </h2>
            </div>
            <div className="flex items-center space-x-1.5 bg-slate-200/80 p-1 rounded-xl text-xs font-bold">
              <button
                type="button"
                onClick={() => setPuViewMode('CONSOLE')}
                className={`px-3 py-1 rounded-lg transition-all ${
                  puViewMode === 'CONSOLE'
                    ? 'bg-white text-slate-900 shadow-xs'
                    : 'text-slate-600 hover:text-slate-900'
                }`}
              >
                Easy A-B-C-D Console
              </button>
              <button
                type="button"
                onClick={() => setPuViewMode('OVERVIEW')}
                className={`px-3 py-1 rounded-lg transition-all ${
                  puViewMode === 'OVERVIEW'
                    ? 'bg-white text-slate-900 shadow-xs'
                    : 'text-slate-600 hover:text-slate-900'
                }`}
              >
                Executive Map & Charts
              </button>
            </div>
          </div>

          {puViewMode === 'CONSOLE' && (
            <PuEasyAbcdConsole currentUser={activeUser} />
          )}
        </div>
      )}

      {/* 2. FIVE COLORFUL TOP KPI CARDS (Matching the Uploaded Screenshot) */}
      <NationalKpiBanners data={jurisdictionKpis} />

      {/* 3. THREE-COLUMN DASHBOARD GRID (Exact Layout from Uploaded Image) */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-5 items-start">
        {/* COLUMN 1 (Wide): Interactive Nigeria Map + State Results Summary Table */}
        <div className="lg:col-span-6 space-y-5">
          {/* Interactive Map */}
          <NigeriaInteractiveSvgMap
            selectedStateName={selectedState?.name}
            onSelectState={(st) => setSelectedState(st)}
          />

          {/* State / LGA / Ward Results Summary Table */}
          {activeUser.role === 'STATE_SUPERVISOR' ? (
            <div className="bg-white rounded-2xl border border-slate-200/90 shadow-sm p-5 space-y-3.5">
              <div className="flex items-center justify-between border-b border-slate-100 pb-3">
                <h3 className="text-base font-black text-slate-900 tracking-tight">
                  {activeUser.state || 'Kebbi'} State LGAs Collation Summary
                </h3>
                <span className="text-xs font-bold text-blue-600">21 LGAs Active</span>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs">
                  <thead>
                    <tr className="border-b border-slate-200 text-slate-500 font-bold">
                      <th className="py-2 px-3">LGA</th>
                      <th className="py-2 px-3">Registered Voters</th>
                      <th className="py-2 px-3">Votes Cast</th>
                      <th className="py-2 px-3">Turnout %</th>
                      <th className="py-2 px-3 text-right">Lead</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {KEBBI_LGAS_REGISTRY.slice(0, 7).map((lga) => (
                      <tr key={lga.name} className="hover:bg-slate-50 transition-colors">
                        <td className="py-2 px-3 font-bold text-slate-900">{lga.name}</td>
                        <td className="py-2 px-3 font-mono">{lga.registeredVoters.toLocaleString()}</td>
                        <td className="py-2 px-3 font-mono">{lga.votesCast.toLocaleString()}</td>
                        <td className="py-2 px-3 font-bold text-emerald-700">{lga.turnoutPercentage}%</td>
                        <td className="py-2 px-3 text-right font-bold text-emerald-700">{lga.leadingParty}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          ) : activeUser.role === 'LGA_COORDINATOR' ? (
            <div className="bg-white rounded-2xl border border-slate-200/90 shadow-sm p-5 space-y-3.5">
              <div className="flex items-center justify-between border-b border-slate-100 pb-3">
                <h3 className="text-base font-black text-slate-900 tracking-tight">
                  {activeUser.lga || 'Argungu'} LGA Wards Summary
                </h3>
                <span className="text-xs font-bold text-blue-600">11 Wards Active</span>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs">
                  <thead>
                    <tr className="border-b border-slate-200 text-slate-500 font-bold">
                      <th className="py-2 px-3">Ward</th>
                      <th className="py-2 px-3">Registered Voters</th>
                      <th className="py-2 px-3">Votes Cast</th>
                      <th className="py-2 px-3">Turnout %</th>
                      <th className="py-2 px-3 text-right">Lead</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {ARGUNGU_WARDS_REGISTRY.map((ward) => (
                      <tr key={ward.name} className="hover:bg-slate-50 transition-colors">
                        <td className="py-2 px-3 font-bold text-slate-900">{ward.name}</td>
                        <td className="py-2 px-3 font-mono">{ward.registeredVoters.toLocaleString()}</td>
                        <td className="py-2 px-3 font-mono">{ward.votesCast.toLocaleString()}</td>
                        <td className="py-2 px-3 font-bold text-emerald-700">{ward.turnoutPercentage}%</td>
                        <td className="py-2 px-3 text-right font-bold text-emerald-700">{ward.leadingParty}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          ) : activeUser.role === 'WARD_SUPERVISOR' ? (
            <div className="bg-white rounded-2xl border border-slate-200/90 shadow-sm p-5 space-y-3.5">
              <div className="flex items-center justify-between border-b border-slate-100 pb-3">
                <h3 className="text-base font-black text-slate-900 tracking-tight">
                  {activeUser.ward || 'Argungu Central I'} Polling Units Summary
                </h3>
                <span className="text-xs font-bold text-emerald-600">28 / 28 Transmitted</span>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs">
                  <thead>
                    <tr className="border-b border-slate-200 text-slate-500 font-bold">
                      <th className="py-2 px-3">PU Code & Name</th>
                      <th className="py-2 px-3">Registered</th>
                      <th className="py-2 px-3">Votes Cast</th>
                      <th className="py-2 px-3">Turnout</th>
                      <th className="py-2 px-3 text-right">Status</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {WARD_PUS_REGISTRY.slice(0, 6).map((pu) => (
                      <tr key={pu.code} className="hover:bg-slate-50 transition-colors">
                        <td className="py-2 px-3">
                          <span className="font-bold text-slate-900 block">{pu.name}</span>
                          <span className="text-[10px] text-slate-400 font-mono">{pu.code}</span>
                        </td>
                        <td className="py-2 px-3 font-mono">{pu.registeredVoters}</td>
                        <td className="py-2 px-3 font-mono font-bold text-emerald-700">{pu.votesCast}</td>
                        <td className="py-2 px-3 font-bold text-slate-800">{pu.turnoutPercentage}%</td>
                        <td className="py-2 px-3 text-right">
                          <span className="px-2 py-0.5 rounded-full text-[10px] font-black uppercase bg-emerald-100 text-emerald-800">
                            {pu.status}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          ) : (
            <StateResultsSummaryTable
              selectedStateName={selectedState?.name}
              onSelectState={(st) => setSelectedState(st)}
            />
          )}
        </div>

        {/* COLUMN 2 (Middle): Turnout Ranking + Donut Chart + Incidents Trend */}
        <div className="lg:col-span-3 space-y-5">
          <TurnoutRankingCard
            title={activeUser.role === 'STATE_SUPERVISOR' ? 'Top LGAs by Turnout' : activeUser.role === 'LGA_COORDINATOR' ? 'Top Wards by Turnout' : 'Top 5 States by Turnout'}
          />

          <PartyVotesDonutChart
            totalVotes={jurisdictionKpis.votesCast}
          />

          <IncidentsTrendCard />
        </div>

        {/* COLUMN 3 (Right): Recent Activity Feed + Issues & Flags */}
        <div className="lg:col-span-3 space-y-5">
          <RecentActivityFeed />

          <IssuesAndFlagsCard />
        </div>
      </div>

      {/* 4. MODAL: Multi-Tier Fast Communication Desk */}
      <MultiTierCommunicationModal
        isOpen={isCommsModalOpen}
        onClose={() => setIsCommsModalOpen(false)}
        currentUser={activeUser}
      />

      {/* 5. BOTTOM FOOTER BAR (Matching Uploaded Screenshot) */}
      <footer className="bg-white rounded-2xl border border-slate-200/90 shadow-xs px-5 py-3 flex flex-col sm:flex-row items-center justify-between text-xs text-slate-500 gap-2">
        <div className="flex flex-wrap items-center space-x-2">
          <span className="font-black text-slate-900">AAMovement</span>
          <span>|</span>
          <span>Nigeria Presidential Election 2027</span>
          <span className="hidden md:inline">•</span>
          <span className="hidden md:inline">Transparency</span>
          <span className="hidden md:inline">•</span>
          <span className="hidden md:inline">Accountability</span>
          <span className="hidden md:inline">•</span>
          <span className="hidden md:inline">Credible Elections</span>
        </div>

        <div className="flex items-center space-x-2 text-[11px] font-medium">
          <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
          <span className="font-bold text-emerald-700">System Online</span>
          <span>•</span>
          <span>Last updated: 16 Jan 2027, 4:32 PM</span>
        </div>
      </footer>
    </div>
  );
};
