'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import {
  Code2,
  Terminal,
  Copy,
  CheckCircle2,
  ExternalLink,
  ShieldCheck,
  Zap,
  Layers,
  ArrowLeft,
  Key,
  Globe,
  Send,
  FileCode,
  Smartphone,
  ChevronRight,
} from 'lucide-react';

export default function DeveloperPortalPage() {
  const [baseUrl, setBaseUrl] = useState('https://atiku2027-situation-room.vercel.app/api/v1');
  const [copiedKey, setCopiedKey] = useState<string | null>(null);

  // Live Console State
  const [puCode, setPuCode] = useState('19-01-01-001');
  const [adcVotes, setAdcVotes] = useState(340);
  const [apcVotes, setApcVotes] = useState(110);
  const [pdpVotes, setPdpVotes] = useState(45);
  const [agentName, setAgentName] = useState('Malam Haruna (Accredited Agent)');
  const [loading, setLoading] = useState(false);
  const [apiResponse, setApiResponse] = useState<any>(null);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      setBaseUrl(`${window.location.origin}/api/v1`);
    }
  }, []);

  const handleCopy = (text: string, keyName: string) => {
    navigator.clipboard.writeText(text);
    setCopiedKey(keyName);
    setTimeout(() => setCopiedKey(null), 3000);
  };

  const handleTestSubmit = async () => {
    setLoading(true);
    setApiResponse(null);
    try {
      const payload = {
        pu_code: puCode,
        party_votes: {
          ADC: Number(adcVotes),
          APC: Number(apcVotes),
          PDP: Number(pdpVotes),
          LP: 10,
          NNPP: 5,
        },
        accredited_voters: Number(adcVotes) + Number(apcVotes) + Number(pdpVotes) + 15,
        rejected_ballots: 0,
        form_ec8a_url: '/sample_ec8a_snap.jpg',
        agent_name: agentName,
        agent_phone: '08031234567',
        bvas_zero_accredited_verified: true,
        agent_signature_confirmed: true,
      };

      const res = await fetch(`${baseUrl}/results`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-API-Key': 'ATIKU2027_LIVE_PU_AGENT_KEY',
        },
        body: JSON.stringify(payload),
      });

      const data = await res.json();
      setApiResponse({ status: res.status, ok: res.ok, data });
    } catch (err: any) {
      setApiResponse({ status: 500, ok: false, data: { error: err.message } });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-[#070D1E] text-slate-100 font-sans selection:bg-purple-600 selection:text-white">
      {/* Top Navigation */}
      <header className="border-b border-purple-900/40 bg-slate-950/80 backdrop-blur-md sticky top-0 z-40">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 h-16 flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <Link
              href="/dashboard"
              className="p-2 rounded-xl bg-slate-900 hover:bg-slate-800 text-slate-300 hover:text-white border border-slate-800 flex items-center gap-1.5 text-xs font-bold transition"
            >
              <ArrowLeft className="w-4 h-4" />
              <span className="hidden sm:inline">Situation Room Dashboard</span>
            </Link>
            <div className="h-5 w-px bg-slate-800" />
            <div className="flex items-center space-x-2">
              <div className="w-8 h-8 rounded-xl bg-purple-950 border border-purple-500/40 flex items-center justify-center text-amber-400">
                <Code2 className="w-4 h-4" />
              </div>
              <span className="font-black text-sm text-white tracking-wide">
                Atiku 2027 Developer API Gateway
              </span>
              <span className="text-[10px] px-2 py-0.5 rounded-full bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-mono font-bold">
                v1.0 REST
              </span>
            </div>
          </div>

          <div className="flex items-center space-x-3">
            <a
              href="/api/v1/docs"
              target="_blank"
              rel="noreferrer"
              className="px-3.5 py-1.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-xs font-mono font-bold text-amber-300 flex items-center gap-1.5 border border-slate-700 transition"
            >
              <FileCode className="w-3.5 h-3.5" />
              <span>OpenAPI JSON</span>
            </a>
          </div>
        </div>
      </header>

      {/* Main Container */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 py-8 space-y-8">
        {/* Hero Section */}
        <div className="bg-gradient-to-r from-purple-950/60 via-slate-900 to-amber-950/40 border border-purple-800/40 rounded-3xl p-6 sm:p-8 relative overflow-hidden shadow-2xl">
          <div className="max-w-3xl space-y-3 relative z-10">
            <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-emerald-500/10 border border-emerald-500/30 text-emerald-300 text-xs font-mono font-bold">
              <Zap className="w-3.5 h-3.5" /> 100% CORS-Enabled &bull; Ready for Flutter, React Native, Swift &amp; Kotlin
            </div>
            <h1 className="text-2xl sm:text-4xl font-black text-white tracking-tight">
              Integrate External Polling Unit Agent Apps
            </h1>
            <p className="text-sm text-slate-300 leading-relaxed">
              Connect your custom mobile applications to the official National Presidential Election Situation Room. Transmit Form EC8A figures, accredited voter counts, and emergency SOS incident beacons with instant live stream delivery.
            </p>
          </div>
        </div>

        {/* API Credentials Box */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="bg-slate-950 border border-slate-800 rounded-2xl p-5 space-y-2">
            <span className="text-[11px] font-mono uppercase tracking-wider text-slate-500 font-bold block">
              Production Gateway Endpoint
            </span>
            <div className="flex items-center justify-between bg-slate-900 p-3 rounded-xl border border-slate-800">
              <span className="text-xs font-mono text-emerald-300 select-all truncate">{baseUrl}</span>
              <button
                onClick={() => handleCopy(baseUrl, 'baseUrl')}
                className="ml-2 px-2.5 py-1 bg-slate-800 hover:bg-slate-700 text-slate-200 text-xs font-bold rounded-lg flex items-center gap-1 shrink-0"
              >
                {copiedKey === 'baseUrl' ? <CheckCircle2 className="w-3.5 h-3.5 text-emerald-400" /> : <Copy className="w-3.5 h-3.5" />}
                <span>{copiedKey === 'baseUrl' ? 'Copied' : 'Copy'}</span>
              </button>
            </div>
          </div>

          <div className="bg-slate-950 border border-slate-800 rounded-2xl p-5 space-y-2">
            <span className="text-[11px] font-mono uppercase tracking-wider text-slate-500 font-bold block flex items-center gap-1">
              <Key className="w-3.5 h-3.5 text-amber-400" /> Production API Header Key
            </span>
            <div className="flex items-center justify-between bg-slate-900 p-3 rounded-xl border border-slate-800">
              <span className="text-xs font-mono text-amber-300 select-all truncate">
                X-API-Key: ATIKU2027_LIVE_PU_AGENT_KEY
              </span>
              <button
                onClick={() => handleCopy('ATIKU2027_LIVE_PU_AGENT_KEY', 'apiKey')}
                className="ml-2 px-2.5 py-1 bg-slate-800 hover:bg-slate-700 text-slate-200 text-xs font-bold rounded-lg flex items-center gap-1 shrink-0"
              >
                {copiedKey === 'apiKey' ? <CheckCircle2 className="w-3.5 h-3.5 text-amber-400" /> : <Copy className="w-3.5 h-3.5" />}
                <span>{copiedKey === 'apiKey' ? 'Copied' : 'Copy'}</span>
              </button>
            </div>
          </div>
        </div>

        {/* Endpoints Reference */}
        <div className="space-y-4">
          <h2 className="text-lg font-black text-white flex items-center gap-2">
            <Layers className="w-5 h-5 text-purple-400" /> Core REST API Endpoints
          </h2>

          <div className="grid grid-cols-1 gap-4">
            {/* 1. Results Submission */}
            <div className="bg-slate-950 border border-slate-800 rounded-2xl p-5 space-y-4">
              <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 border-b border-slate-800 pb-3">
                <div className="flex items-center gap-3">
                  <span className="px-2.5 py-1 rounded-lg bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-mono text-xs font-black">
                    POST
                  </span>
                  <span className="text-sm font-mono font-bold text-white">/results</span>
                </div>
                <span className="text-xs text-slate-400 font-bold">
                  Form EC8A Live Transmission &amp; Mathematical Collation
                </span>
              </div>

              <p className="text-xs text-slate-300 leading-relaxed">
                Transmits Polling Unit results. Automatically checks against official statutory registered voters, validates mathematical balance (Total Cast = Accredited), flags over-voting under Section 51 of Electoral Act 2022, and broadcasts in real time to the National Situation Room.
              </p>

              <div>
                <span className="text-[10px] uppercase font-mono font-bold text-slate-500 block mb-1">
                  Example JSON Request Body:
                </span>
                <pre className="p-4 bg-slate-900 border border-slate-800 rounded-xl text-xs font-mono text-emerald-300 overflow-x-auto leading-relaxed">
{`{
  "pu_code": "19-01-01-001",
  "party_votes": {
    "ADC": 340,
    "APC": 110,
    "PDP": 45,
    "LP": 10,
    "NNPP": 5
  },
  "accredited_voters": 510,
  "rejected_ballots": 0,
  "form_ec8a_url": "https://storage.atiku2027.org/ec8a/19-01-01-001.jpg",
  "agent_name": "Malam Haruna Bello",
  "agent_phone": "08031234567",
  "latitude": 11.9964,
  "longitude": 8.5167,
  "agent_signature_confirmed": true,
  "bvas_zero_accredited_verified": true
}`}
                </pre>
              </div>
            </div>

            {/* 2. PU Lookup */}
            <div className="bg-slate-950 border border-slate-800 rounded-2xl p-5 space-y-4">
              <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 border-b border-slate-800 pb-3">
                <div className="flex items-center gap-3">
                  <span className="px-2.5 py-1 rounded-lg bg-sky-500/20 text-sky-300 border border-sky-500/30 font-mono text-xs font-black">
                    GET
                  </span>
                  <span className="text-sm font-mono font-bold text-white">/pu/lookup?pu_code=...</span>
                </div>
                <span className="text-xs text-slate-400 font-bold">
                  Statutory Delimitation &amp; Certified Registered Voters Lookup
                </span>
              </div>

              <p className="text-xs text-slate-300 leading-relaxed">
                Enables external mobile apps to look up official Polling Unit name, Ward, LGA, State, official 18 registered INEC parties, and unchangeable statutory registered voters baseline before result collation.
              </p>

              <div>
                <span className="text-[10px] uppercase font-mono font-bold text-slate-500 block mb-1">
                  Example cURL Command:
                </span>
                <pre className="p-4 bg-slate-900 border border-slate-800 rounded-xl text-xs font-mono text-sky-300 overflow-x-auto leading-relaxed">
{`curl -X GET "${baseUrl}/pu/lookup?pu_code=19-01-01-001" \\
  -H "X-API-Key: ATIKU2027_LIVE_PU_AGENT_KEY"`}
                </pre>
              </div>
            </div>

            {/* 3. Emergency SOS */}
            <div className="bg-slate-950 border border-slate-800 rounded-2xl p-5 space-y-4">
              <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 border-b border-slate-800 pb-3">
                <div className="flex items-center gap-3">
                  <span className="px-2.5 py-1 rounded-lg bg-rose-500/20 text-rose-300 border border-rose-500/30 font-mono text-xs font-black">
                    POST
                  </span>
                  <span className="text-sm font-mono font-bold text-white">/incidents</span>
                </div>
                <span className="text-xs text-slate-400 font-bold">
                  Emergency Incident &amp; BVAS Malfunction Beacon
                </span>
              </div>

              <p className="text-xs text-slate-300 leading-relaxed">
                Sends priority SOS alarms (BVAS failure, logistics delay, violence, intimidation) with GPS coordinates to the Situation Room Rapid Response desk.
              </p>
            </div>
          </div>
        </div>

        {/* Live Interactive API Tester Console */}
        <div className="bg-slate-950 border border-slate-800 rounded-3xl p-6 sm:p-8 space-y-6">
          <div className="flex items-center justify-between border-b border-slate-800 pb-4">
            <div>
              <h2 className="text-lg font-black text-white flex items-center gap-2">
                <Terminal className="w-5 h-5 text-amber-400" /> Interactive Live API Console
              </h2>
              <p className="text-xs text-slate-400 mt-0.5">
                Test sending a real Form EC8A submission to the live Situation Room API
              </p>
            </div>
            <span className="text-[10px] px-2.5 py-1 bg-emerald-500/20 text-emerald-300 rounded-full font-mono font-bold">
              Live Gateway Active
            </span>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="text-xs font-bold text-slate-300 block mb-1.5">Polling Unit Code</label>
              <input
                type="text"
                value={puCode}
                onChange={(e) => setPuCode(e.target.value)}
                className="w-full px-3.5 py-2.5 bg-slate-900 border border-slate-700 rounded-xl text-xs font-mono text-white"
              />
            </div>

            <div>
              <label className="text-xs font-bold text-slate-300 block mb-1.5">Agent Full Name</label>
              <input
                type="text"
                value={agentName}
                onChange={(e) => setAgentName(e.target.value)}
                className="w-full px-3.5 py-2.5 bg-slate-900 border border-slate-700 rounded-xl text-xs text-white"
              />
            </div>

            <div>
              <label className="text-xs font-bold text-emerald-400 block mb-1.5">ADC Candidate Votes</label>
              <input
                type="number"
                value={adcVotes}
                onChange={(e) => setAdcVotes(Number(e.target.value))}
                className="w-full px-3.5 py-2.5 bg-slate-900 border border-slate-700 rounded-xl text-xs font-mono font-bold text-emerald-300"
              />
            </div>

            <div>
              <label className="text-xs font-bold text-slate-300 block mb-1.5">APC &amp; PDP Votes</label>
              <div className="flex gap-2">
                <input
                  type="number"
                  value={apcVotes}
                  onChange={(e) => setApcVotes(Number(e.target.value))}
                  placeholder="APC"
                  className="w-1/2 px-3.5 py-2.5 bg-slate-900 border border-slate-700 rounded-xl text-xs font-mono text-white"
                />
                <input
                  type="number"
                  value={pdpVotes}
                  onChange={(e) => setPdpVotes(Number(e.target.value))}
                  placeholder="PDP"
                  className="w-1/2 px-3.5 py-2.5 bg-slate-900 border border-slate-700 rounded-xl text-xs font-mono text-white"
                />
              </div>
            </div>
          </div>

          <button
            onClick={handleTestSubmit}
            disabled={loading}
            className="w-full py-3.5 bg-gradient-to-r from-emerald-600 via-teal-600 to-emerald-600 hover:from-emerald-500 hover:to-teal-500 text-white font-black text-sm rounded-xl shadow-lg flex items-center justify-center gap-2 transition active:scale-98 disabled:opacity-50"
          >
            <Send className="w-4 h-4" />
            <span>{loading ? 'Transmitting Request...' : 'Transmit Test Result via POST /api/v1/results'}</span>
          </button>

          {apiResponse && (
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-xs font-bold text-slate-300">HTTP Response:</span>
                <span
                  className={`px-2.5 py-0.5 rounded text-[10px] font-mono font-black ${
                    apiResponse.ok
                      ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
                      : 'bg-rose-500/20 text-rose-300 border border-rose-500/30'
                  }`}
                >
                  HTTP {apiResponse.status} {apiResponse.ok ? 'CREATED' : 'ERROR'}
                </span>
              </div>
              <pre className="p-4 bg-black/60 rounded-2xl border border-slate-800 text-xs font-mono text-slate-300 overflow-x-auto leading-relaxed max-h-60">
                {JSON.stringify(apiResponse.data, null, 2)}
              </pre>
            </div>
          )}
        </div>
      </main>
    </div>
  );
}
