'use client';

import React, { useState, useEffect } from 'react';
import {
  Wifi,
  WifiOff,
  AlertOctagon,
  CheckCircle2,
  Clock,
  RotateCw,
  LogOut,
  ArrowLeft,
  Scale,
  QrCode,
  Smartphone,
  ShieldCheck,
  Check
} from 'lucide-react';

import { Step1ArrivalReport } from '@/components/agent/Step1ArrivalReport';
import { Step2BvasZeroCount } from '@/components/agent/Step2BvasZeroCount';
import { Step3OngoingVoting } from '@/components/agent/Step3OngoingVoting';
import { Step4ClosingQueueInfo } from '@/components/agent/Step4ClosingQueueInfo';
import { Step5SortingProcess } from '@/components/agent/Step5SortingProcess';
import { Step6ResultsData } from '@/components/agent/Step6ResultsData';
import { Step7FinalSuccess } from '@/components/agent/Step7FinalSuccess';

import { IncidentBeaconModal } from '@/components/agent/IncidentBeaconModal';
import { AgentLegalRightsModal } from '@/components/agent/AgentLegalRightsModal';
import { MobileAppCenterModal } from '@/components/common/MobileAppCenterModal';
import { AssistantChatbot } from '@/components/common/AssistantChatbot';
import { enqueueOfflineItem, getOfflineQueue, dequeueOfflineItem } from '@/lib/offlineQueue';
import { getStatutoryRegisteredVotersForPu, POLLING_UNITS_BY_WARD, NIGERIAN_STATES } from '@/lib/electoralData';
import type { UserSession } from '@/types';
import { logout } from '@/lib/clientAuth';

function resolvePuName(code: string) {
  const wardId = code.split('-').slice(0, 3).join('-');
  return POLLING_UNITS_BY_WARD[wardId]?.find((pu) => pu.pu_code === code)?.pu_name || `Polling Unit ${code}`;
}

export default function AgentWorkspace({ user }: { user: UserSession }) {
  // Polling Unit Context
  const puCode = user.assigned_scope_id;
  const puName = resolvePuName(puCode);
  const registeredVoters = getStatutoryRegisteredVotersForPu(puCode);
  const agentName = user.full_name;

  // 7-Page Workflow Active Step State (1 to 7)
  const [activeStep, setActiveStep] = useState<number>(1);
  const [completedSteps, setCompletedSteps] = useState<Record<number, boolean>>({
    1: true,
    2: true,
  });

  // Offline / Network States
  const [isOnline, setIsOnline] = useState<boolean>(true);
  const [pendingQueueCount, setPendingQueueCount] = useState<number>(0);
  const [syncing, setSyncing] = useState<boolean>(false);
  const [toastMsg, setToastMsg] = useState<string | null>(null);

  // Emergency & Auxiliary Modals
  const [showBeacon, setShowBeacon] = useState<boolean>(false);
  const [showMobileAppModal, setShowMobileAppModal] = useState<boolean>(false);
  const [showLegalModal, setShowLegalModal] = useState<boolean>(false);

  // Monitor Network Connectivity & Handle Direct Magic Links
  useEffect(() => {
    if (typeof window !== 'undefined') {
      setIsOnline(navigator.onLine);
      const handleOnline = () => {
        setIsOnline(true);
        triggerSync();
      };
      const handleOffline = () => setIsOnline(false);

      window.addEventListener('online', handleOnline);
      window.addEventListener('offline', handleOffline);

      // Check offline queue
      getOfflineQueue().then((items) => setPendingQueueCount(items.length));

      return () => {
        window.removeEventListener('online', handleOnline);
        window.removeEventListener('offline', handleOffline);
      };
    }
  }, []);

  const triggerSync = async () => {
    setSyncing(true);
    try {
      const items = await getOfflineQueue();
      for (const item of items) {
        if (item.type === 'RESULT_EC8A') {
          try {
            await fetch('/api/results', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(item.payload),
            });
          } catch (_) {}

          try {
            await 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: item.payload }),
            });
          } catch (_) {}

          await dequeueOfflineItem(item.id);
        }
      }
      const remaining = await getOfflineQueue();
      setPendingQueueCount(remaining.length);
      setToastMsg('All offline submissions synced successfully!');
      setTimeout(() => setToastMsg(null), 3000);
    } catch (err) {
      console.error('Sync error:', err);
    } finally {
      setSyncing(false);
    }
  };

  const handleResultSubmit = async (data: any): Promise<boolean> => {
    // Normalize payload to satisfy both Step6 format and /api/results schema
    const votesObj = data.party_votes || data.votes || {};
    let totalVotes = Number(data.total_valid_votes) || 0;
    if (totalVotes === 0) {
      for (const v of Object.values(votesObj)) {
        totalVotes += Number(v) || 0;
      }
    }
    const accredited = data.accredited_voters !== undefined ? Number(data.accredited_voters) : totalVotes;
    const statutoryVoters = data.registered_voters || getStatutoryRegisteredVotersForPu(data.pu_code || puCode);

    const normalizedData = {
      ...data,
      pu_code: data.pu_code || puCode,
      registered_voters: statutoryVoters,
      accredited_voters: accredited,
      party_votes: votesObj,
      votes: votesObj,
      total_valid_votes: totalVotes,
      total_votes_cast: totalVotes + (Number(data.rejected_ballots) || 0),
      rejected_ballots: Number(data.rejected_ballots) || 0,
      form_ec8a_url: data.form_ec8a_url || data.physical_ec8a_photo || '/sample_ec8a_snap.jpg',
      physical_ec8a_photo: data.physical_ec8a_photo || data.form_ec8a_url || '/sample_ec8a_snap.jpg',
      agent_name: agentName,
      submitted_at: new Date().toISOString(),
    };

    let apiSuccess = false;
    let resJson: any = null;

    try {
      const res = await fetch('/api/results', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(normalizedData),
      });
      if (res.ok) {
        resJson = await res.json();
        apiSuccess = true;
      }
    } catch (err) {
      console.warn('API post error:', err);
    }

    const payloadResult = (resJson && resJson.result) ? resJson.result : normalizedData;

    // 1. Same-device tab sync via BroadcastChannel
    if (typeof window !== 'undefined' && 'BroadcastChannel' in window) {
      try {
        const channel = new BroadcastChannel('election_situation_room_stream');
        channel.postMessage({ type: 'NEW_PU_RESULT', result: payloadResult });
        channel.close();
      } catch (_) {}
    }

    // 2. Real-time cross-device sync via ntfy pubsub (Phone to Situation Room)
    let ntfySuccess = false;
    try {
      const ntfyRes = await 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: payloadResult }),
      });
      if (ntfyRes.ok) ntfySuccess = true;
    } catch (_) {}

    if (apiSuccess || ntfySuccess) {
      setCompletedSteps((prev) => ({ ...prev, 6: true }));
      setToastMsg('⚡ Form EC8A Result transmitted live to National Situation Room!');
      setTimeout(() => setToastMsg(null), 4000);
      return true;
    } else {
      // Offline fallback: queue for sync when network is restored
      await enqueueOfflineItem('RESULT_EC8A', normalizedData);
      setPendingQueueCount((prev) => prev + 1);
      setCompletedSteps((prev) => ({ ...prev, 6: true }));
      setToastMsg('Network offline. Form EC8A saved securely in offline cache! Will transmit once connection is restored.');
      setTimeout(() => setToastMsg(null), 4000);
      return true;
    }
  };

  const handleLogout = async () => {
    try {
      await logout();
    } catch (error: unknown) {
      setToastMsg(error instanceof Error ? error.message : 'Unable to sign out. Please try again.');
    }
  };

  // Titles for the 7 pages matching diagram
  const getPageTitle = (step: number) => {
    switch (step) {
      case 1:
        return 'Arrival Report';
      case 2:
        return 'BVAS Zero Count';
      case 3:
        return 'Ongoing Voting Status';
      case 4:
        return 'Closing & Queue Info';
      case 5:
        return 'Sorting Process';
      case 6:
        return 'Results Data & e-EC8A';
      case 7:
        return 'Final Submission Success';
      default:
        return 'Polling Unit Agent';
    }
  };

  const stepsList = [
    { num: 1, label: '1. Morning', sub: 'Arrival' },
    { num: 2, label: '2. BVAS 0', sub: 'Zero Check' },
    { num: 3, label: '3. Turnout', sub: 'Ongoing' },
    { num: 4, label: '4. Cutoff', sub: '2:30 PM' },
    { num: 5, label: '5. Sorting', sub: 'Counting' },
    { num: 6, label: '6. Results', sub: 'e-EC8A' },
    { num: 7, label: '7. Done', sub: 'Submit' },
  ];

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100 flex flex-col pb-12 font-sans select-none">
      {/* Dark Emerald Header Bar (Matching Image Diagram UX: #065F46) */}
      <header className="sticky top-0 z-30 bg-[#065F46] text-white px-4 py-3 shadow-lg border-b border-emerald-800">
        <div className="max-w-md mx-auto flex items-center justify-between">
          <div className="flex items-center space-x-2.5">
            {/* Back Navigation Button ← */}
            {activeStep > 1 && (
              <button
                type="button"
                onClick={() => setActiveStep((prev) => Math.max(1, prev - 1))}
                className="p-1 rounded-lg hover:bg-emerald-800 text-white transition"
                title="Previous Page"
              >
                <ArrowLeft className="w-5 h-5" />
              </button>
            )}
            <div>
              <h1 className="text-sm font-black tracking-wide flex items-center gap-1.5">
                <span>{getPageTitle(activeStep)}</span>
              </h1>
              <p className="text-[11px] font-bold text-amber-300 truncate max-w-[280px]">
                {puName}
              </p>
              <p className="text-[10px] text-emerald-100/90 font-mono truncate max-w-[280px]">
                PU [{puCode}] &bull; {(() => {
                  const prefix = puCode.split('-')[0];
                  const st = NIGERIAN_STATES.find(s => s.id === prefix || s.id === prefix?.padStart(2, '0'));
                  return st ? `${st.name} State (INEC Code: ${st.id})` : `State ${prefix}`;
                })()} &bull; <strong className="text-amber-200">{registeredVoters.toLocaleString()} Voters 🔒</strong>
              </p>
              <p className="text-[9px] text-purple-200 font-extrabold tracking-tight">
                Powered by GetoCore Digital Innovation
              </p>
            </div>
          </div>

          <div className="flex items-center space-x-1.5">
            {/* Legal Rights Card Modal Button */}
            <button
              type="button"
              onClick={() => setShowLegalModal(true)}
              className="px-2 py-1 rounded-full text-[10px] font-bold bg-emerald-900/90 text-amber-300 border border-emerald-600 transition flex items-center gap-1"
              title="Legal Rights Card"
            >
              <Scale className="w-3 h-3 text-amber-300" />
              <span className="hidden sm:inline">Rights</span>
            </button>

            {/* Online / Offline status badge */}
            <div
              className={`flex items-center gap-1 px-2 py-1 rounded-full text-[10px] font-bold border ${
                isOnline
                  ? 'bg-emerald-950/80 border-emerald-400 text-emerald-200'
                  : 'bg-red-950/80 border-red-400 text-red-200'
              }`}
            >
              {isOnline ? <Wifi className="w-3 h-3" /> : <WifiOff className="w-3 h-3" />}
              <span>{isOnline ? 'Online' : 'Offline'}</span>
            </div>

            {/* Offline sync button if pending */}
            {pendingQueueCount > 0 && (
              <button
                type="button"
                onClick={triggerSync}
                disabled={syncing || !isOnline}
                className="flex items-center gap-1 px-2 py-1 rounded-full text-[10px] font-bold bg-amber-500 text-slate-950 border border-amber-400 animate-pulse"
              >
                <RotateCw className={`w-3 h-3 ${syncing ? 'animate-spin' : ''}`} />
                <span>Sync ({pendingQueueCount})</span>
              </button>
            )}

            {/* App QR Button */}
            <button
              type="button"
              onClick={() => setShowMobileAppModal(true)}
              className="p-1 rounded-lg bg-emerald-800 hover:bg-emerald-700 text-emerald-100 transition"
              title="Mobile App QR Code"
            >
              <QrCode className="w-4 h-4" />
            </button>

            {/* Logout Button */}
            <a href="/bvas-info" className="rounded-lg border border-emerald-700 px-2 py-1 text-xs font-semibold text-white hover:bg-emerald-700">BVAS info</a>
            <a href="/bvas-report-1" className="rounded-lg border border-emerald-700 px-2 py-1 text-xs font-semibold text-white hover:bg-emerald-700">BVAS Report 1</a>
            <a href="/bvas-report-2" className="rounded-lg border border-emerald-700 px-2 py-1 text-xs font-semibold text-white hover:bg-emerald-700">Turn Out</a>
            <a href="/bvas-report-3" className="rounded-lg border border-emerald-700 px-2 py-1 text-xs font-semibold text-white hover:bg-emerald-700">Sign Off</a>
            <a href="/incidents" className="rounded-lg border border-emerald-700 px-2 py-1 text-xs font-semibold text-white hover:bg-emerald-700">Incidents</a>
            <a href="/registered-voters" className="rounded-lg border border-emerald-700 px-2 py-1 text-xs font-semibold text-white hover:bg-emerald-700">Registered voters</a>
            <button
              type="button"
              onClick={handleLogout}
              className="flex items-center gap-1 px-2 py-1 rounded-lg bg-rose-900/80 hover:bg-rose-800 text-rose-200 border border-rose-700 text-[10px] font-bold transition shadow-xs"
              title="Exit & Sign Out"
            >
              <LogOut className="w-3.5 h-3.5" />
              <span>Exit</span>
            </button>
          </div>
        </div>
      </header>

      {/* Emergency Beacon Action Bar */}
      <div className="max-w-md mx-auto w-full px-4 pt-3">
        <button
          type="button"
          onClick={() => setShowBeacon(true)}
          className="w-full py-2 px-3 rounded-xl bg-gradient-to-r from-red-800 via-red-700 to-red-800 hover:from-red-700 hover:to-red-600 border border-red-600 text-white font-extrabold text-[11px] uppercase tracking-wider shadow flex items-center justify-between transition"
        >
          <div className="flex items-center space-x-2">
            <AlertOctagon className="w-3.5 h-3.5 text-white animate-pulse" />
            <span>Emergency SOS Beacon</span>
          </div>
          <span className="text-[9px] bg-black/40 px-2 py-0.5 rounded font-bold">
            Alert HQ &rarr;
          </span>
        </button>
      </div>

      {/* Notification Toast */}
      {toastMsg && (
        <div className="max-w-md mx-auto w-full px-4 mt-2">
          <div className="p-2.5 bg-emerald-900 border border-emerald-500 text-emerald-100 text-xs rounded-xl flex items-center gap-2 shadow-lg">
            <CheckCircle2 className="w-4 h-4 shrink-0 text-emerald-300" />
            <span>{toastMsg}</span>
          </div>
        </div>
      )}

      {/* Main 7-Page Workspace */}
      <main className="max-w-md mx-auto w-full px-4 mt-3 space-y-4">
        {/* 7-Step Navigation Bar */}
        <div className="bg-slate-900 border border-slate-800 rounded-2xl p-1.5 shadow-sm">
          <div className="grid grid-cols-7 gap-1">
            {stepsList.map((st) => (
              <button
                key={st.num}
                type="button"
                onClick={() => setActiveStep(st.num)}
                className={`py-1.5 px-0.5 rounded-xl text-center transition flex flex-col items-center justify-center ${
                  activeStep === st.num
                    ? 'bg-[#065F46] text-white font-black shadow'
                    : completedSteps[st.num]
                    ? 'bg-slate-950 border border-emerald-700/50 text-emerald-400 font-bold'
                    : 'bg-slate-950/60 text-slate-400 hover:text-slate-200'
                }`}
              >
                <span className="text-[9px] font-bold leading-none truncate w-full text-center">
                  {st.num}
                </span>
                <span className="text-[8px] truncate w-full text-center mt-0.5 opacity-90">
                  {st.label.split(' ')[1] || st.label}
                </span>
              </button>
            ))}
          </div>
        </div>

        {/* 7 Pages Switcher */}
        <div>
          {activeStep === 1 && (
            <Step1ArrivalReport
              puCode={puCode}
              onNext={(data) => {
                setCompletedSteps((prev) => ({ ...prev, 1: true }));
                setActiveStep(2);
              }}
            />
          )}

          {activeStep === 2 && (
            <Step2BvasZeroCount
              puCode={puCode}
              onNext={(data) => {
                setCompletedSteps((prev) => ({ ...prev, 2: true }));
                setActiveStep(3);
              }}
            />
          )}

          {activeStep === 3 && (
            <Step3OngoingVoting
              puCode={puCode}
              registeredVoters={registeredVoters}
              onNext={(data) => {
                setCompletedSteps((prev) => ({ ...prev, 3: true }));
                setActiveStep(4);
              }}
            />
          )}

          {activeStep === 4 && (
            <Step4ClosingQueueInfo
              puCode={puCode}
              onNext={(data) => {
                setCompletedSteps((prev) => ({ ...prev, 4: true }));
                setActiveStep(5);
              }}
            />
          )}

          {activeStep === 5 && (
            <Step5SortingProcess
              puCode={puCode}
              onNext={(data) => {
                setCompletedSteps((prev) => ({ ...prev, 5: true }));
                setActiveStep(6);
              }}
            />
          )}

          {activeStep === 6 && (
            <Step6ResultsData
              puCode={puCode}
              registeredVoters={registeredVoters}
              onSubmit={handleResultSubmit}
              onNext={() => {
                setCompletedSteps((prev) => ({ ...prev, 6: true }));
                setActiveStep(7);
              }}
            />
          )}

          {activeStep === 7 && (
            <Step7FinalSuccess
              puCode={puCode}
              onLogout={handleLogout}
            />
          )}
        </div>
      </main>

      {/* Emergency Beacon Modal */}
      <IncidentBeaconModal
        isOpen={showBeacon}
        onClose={() => setShowBeacon(false)}
        puCode={puCode}
        puName={puName}
        onIncidentDispatched={(inc) => {
          setToastMsg(`Emergency Beacon Dispatched: ${inc.category}`);
          setTimeout(() => setToastMsg(null), 4000);
        }}
      />

      {/* Multilingual AI Guidance Assistant */}
      <AssistantChatbot defaultRole="PU_AGENT" />

      {/* Mobile App Center Modal */}
      <MobileAppCenterModal
        isOpen={showMobileAppModal}
        onClose={() => setShowMobileAppModal(false)}
      />

      {/* Agent Legal Rights Modal */}
      <AgentLegalRightsModal
        isOpen={showLegalModal}
        onClose={() => setShowLegalModal(false)}
        puCode={puCode}
      />

      {/* Footer */}
      <footer className="mt-8 text-center text-[10px] text-slate-500 pb-4">
        <span className="text-emerald-400 font-bold">His Excellency Atiku Abubakar Presidential Campaign (ADC 🤝)</span>
        <span className="mx-1.5">&bull;</span>
        <span>Powered by GetoCore Digital Innovation</span>
      </footer>
    </div>
  );
}
