'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import Navbar from '@/components/layout/Navbar';
import Footer from '@/components/layout/Footer';
import {
  Code,
  Terminal,
  ShieldCheck,
  Copy,
  Check,
  Play,
  Key,
  Lock,
  Layers,
  ArrowRight,
  Send,
  AlertCircle,
} from 'lucide-react';

export default function DocsPage() {
  const [user, setUser] = useState<any>(null);
  const [selectedLanguage, setSelectedLanguage] = useState<'curl' | 'js' | 'python' | 'php'>('curl');
  const [activeEndpoint, setActiveEndpoint] = useState<'nin' | 'phone-nin'>('nin');
  const [copiedCode, setCopiedCode] = useState(false);

  // Live sandbox runner inside docs
  const [testNin, setTestNin] = useState('12345678901');
  const [apiKeyInput, setApiKeyInput] = useState('sk_test_demo1234567890abcdef12345678');
  const [loading, setLoading] = useState(false);
  const [response, setResponse] = useState<any>(null);

  useEffect(() => {
    fetch('/api/v1/account')
      .then((r) => r.json())
      .then((d) => {
        if (d.success) setUser(d.data.user);
      })
      .catch(() => {});
  }, []);

  const isVerificationUser = user?.role === 'VERIFICATION_USER';

  const codeSnippets = {
    nin: {
      curl: `curl -X POST https://api.ninauth.ng/api/v1/verification/nin \\
  -H "Authorization: Bearer ${apiKeyInput}" \\
  -H "Content-Type: application/json" \\
  -d '{
    "nin": "${testNin}",
    "firstname": "Aisha",
    "surname": "Bello"
  }'`,
      js: `const response = await fetch("https://api.ninauth.ng/api/v1/verification/nin", {
  method: "POST",
  headers: {
    "Authorization": "Bearer ${apiKeyInput}",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    nin: "${testNin}",
    firstname: "Aisha",
    surname: "Bello"
  })
});
const data = await response.json();
console.log(data);`,
      python: `import requests

url = "https://api.ninauth.ng/api/v1/verification/nin"
headers = {
    "Authorization": "Bearer ${apiKeyInput}",
    "Content-Type": "application/json"
}
payload = {
    "nin": "${testNin}",
    "firstname": "Aisha",
    "surname": "Bello"
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())`,
      php: `<?php
$ch = curl_init('https://api.ninauth.ng/api/v1/verification/nin');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ${apiKeyInput}',
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'nin' => '${testNin}',
    'firstname' => 'Aisha',
    'surname' => 'Bello'
]));

$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>`,
    },
    'phone-nin': {
      curl: `curl -X POST https://api.ninauth.ng/api/v1/verification/phone-nin \\
  -H "Authorization: Bearer ${apiKeyInput}" \\
  -H "Content-Type: application/json" \\
  -d '{
    "nin": "${testNin}",
    "phoneNumber": "08034567890"
  }'`,
      js: `const response = await fetch("https://api.ninauth.ng/api/v1/verification/phone-nin", {
  method: "POST",
  headers: {
    "Authorization": "Bearer ${apiKeyInput}",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    nin: "${testNin}",
    phoneNumber: "08034567890"
  })
});
const data = await response.json();`,
      python: `import requests

response = requests.post(
    "https://api.ninauth.ng/api/v1/verification/phone-nin",
    headers={"Authorization": "Bearer ${apiKeyInput}"},
    json={"nin": "${testNin}", "phoneNumber": "08034567890"}
)
print(response.json())`,
      php: `<?php
// Phone to NIN Linkage Match
$ch = curl_init('https://api.ninauth.ng/api/v1/verification/phone-nin');
// ...
?>`,
    },
  };

  const currentSnippet = codeSnippets[activeEndpoint][selectedLanguage];

  const handleCopy = () => {
    navigator.clipboard.writeText(currentSnippet);
    setCopiedCode(true);
    setTimeout(() => setCopiedCode(false), 2000);
  };

  const handleExecuteSandbox = async () => {
    setLoading(true);
    try {
      const endpoint =
        activeEndpoint === 'nin'
          ? '/api/v1/verification/nin'
          : '/api/v1/verification/phone-nin';

      const payload =
        activeEndpoint === 'nin'
          ? { nin: testNin, firstname: 'Aisha', surname: 'Bello' }
          : { nin: testNin, phoneNumber: '08034567890' };

      const res = await fetch(endpoint, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${apiKeyInput}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
      });
      const data = await res.json();
      setResponse(data);
    } catch (err: any) {
      setResponse({ success: false, error: { message: err.message } });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-[#f7f9fa] dark:bg-[#070b14] text-[#1e293b] dark:text-slate-100 font-sans flex flex-col">
      <Navbar />

      <main className="flex-1 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10 space-y-8 w-full">
        {/* Standard User Access Gate Notification */}
        {isVerificationUser && (
          <div className="p-6 rounded-2xl bg-amber-50 dark:bg-amber-950/40 border border-amber-300 dark:border-amber-700/60 space-y-3">
            <div className="flex items-center gap-2.5">
              <AlertCircle className="w-5 h-5 text-amber-600 shrink-0" />
              <h3 className="text-sm font-bold text-amber-900 dark:text-amber-200">
                Standard User Access Mode
              </h3>
            </div>
            <p className="text-xs text-amber-800 dark:text-amber-300 leading-relaxed">
              API documentation and programmatic REST integration are reserved for <strong>API Users</strong>. You can perform verifications through the web dashboard or submit a request to upgrade your account.
            </p>
            <div className="pt-1">
              <Link
                href="/dashboard/request-api"
                className="inline-flex items-center gap-1.5 px-5 py-2 rounded-full bg-[#00875a] text-white text-xs font-semibold hover:bg-[#00693e] transition-colors"
              >
                <Send className="w-3.5 h-3.5" />
                <span>Submit API Access Application</span>
              </Link>
            </div>
          </div>
        )}

        {/* Documentation Header */}
        <div className="space-y-2">
          <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-[#e8f5e9] dark:bg-emerald-950/60 text-[#00693e] dark:text-emerald-300 text-xs font-bold font-mono">
            <span>REST API v1 Reference</span>
          </div>
          <h1 className="text-3xl font-extrabold text-[#0f172a] dark:text-white tracking-tight">
            SmartAuth Identity Verification API
          </h1>
          <p className="text-sm text-[#64748b] dark:text-slate-400 max-w-3xl">
            Integrate instant Nigerian National Identification Number (NIN) verification, Phone-to-NIN matching, and HMAC webhook events into your applications.
          </p>
        </div>

        {/* Endpoints & Code Runner Grid */}
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
          {/* Left: Interactive Code Samples & Live Runner */}
          <div className="lg:col-span-8 space-y-6">
            {/* Endpoint Selector Tabs */}
            <div className="flex border-b border-slate-200 dark:border-slate-800 space-x-4">
              <button
                type="button"
                onClick={() => setActiveEndpoint('nin')}
                className={`pb-3 text-xs font-bold transition-all border-b-2 ${
                  activeEndpoint === 'nin'
                    ? 'border-[#00875a] text-[#00875a] dark:text-emerald-400'
                    : 'border-transparent text-slate-500 hover:text-slate-800'
                }`}
              >
                POST /api/v1/verification/nin
              </button>
              <button
                type="button"
                onClick={() => setActiveEndpoint('phone-nin')}
                className={`pb-3 text-xs font-bold transition-all border-b-2 ${
                  activeEndpoint === 'phone-nin'
                    ? 'border-[#00875a] text-[#00875a] dark:text-emerald-400'
                    : 'border-transparent text-slate-500 hover:text-slate-800'
                }`}
              >
                POST /api/v1/verification/phone-nin
              </button>
            </div>

            {/* Code Box */}
            <div className="nin-card overflow-hidden">
              <div className="bg-slate-900 px-4 py-2.5 border-b border-slate-800 flex items-center justify-between">
                <div className="flex gap-2">
                  {(['curl', 'js', 'python', 'php'] as const).map((lang) => (
                    <button
                      key={lang}
                      type="button"
                      onClick={() => setSelectedLanguage(lang)}
                      className={`px-3 py-1 rounded-lg text-xs font-mono font-bold transition-all ${
                        selectedLanguage === lang
                          ? 'bg-[#00875a] text-white'
                          : 'text-slate-400 hover:text-slate-200'
                      }`}
                    >
                      {lang.toUpperCase()}
                    </button>
                  ))}
                </div>

                <button
                  onClick={handleCopy}
                  className="text-slate-400 hover:text-white p-1 text-xs flex items-center gap-1 font-mono"
                >
                  {copiedCode ? <Check className="w-3.5 h-3.5 text-emerald-400" /> : <Copy className="w-3.5 h-3.5" />}
                  <span>{copiedCode ? 'Copied' : 'Copy'}</span>
                </button>
              </div>

              <div className="bg-[#050811] p-4 text-xs font-mono text-slate-200 overflow-x-auto">
                <pre>{currentSnippet}</pre>
              </div>
            </div>

            {/* In-Docs Live Runner */}
            <div className="nin-card p-6 space-y-4">
              <div className="flex items-center justify-between border-b border-slate-100 dark:border-slate-800/80 pb-3">
                <h3 className="text-sm font-bold text-[#0f172a] dark:text-white flex items-center gap-2">
                  <Play className="w-4 h-4 text-[#00875a] fill-current" />
                  Live Sandbox Request Runner
                </h3>
                <span className="text-[10px] font-mono font-bold text-emerald-600 bg-emerald-50 dark:bg-emerald-950/40 px-2 py-0.5 rounded">
                  SANDBOX
                </span>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
                    API Secret Key
                  </label>
                  <input
                    type="text"
                    value={apiKeyInput}
                    onChange={(e) => setApiKeyInput(e.target.value)}
                    className="w-full bg-[#f8fafc] dark:bg-slate-900 border border-[#e2e8f0] dark:border-slate-700 rounded-xl px-3.5 py-2 text-xs font-mono text-[#0f172a] dark:text-white focus:outline-none focus:border-[#00875a]"
                  />
                </div>

                <div>
                  <label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
                    Test 11-Digit NIN
                  </label>
                  <input
                    type="text"
                    value={testNin}
                    onChange={(e) => setTestNin(e.target.value)}
                    className="w-full bg-[#f8fafc] dark:bg-slate-900 border border-[#e2e8f0] dark:border-slate-700 rounded-xl px-3.5 py-2 text-xs font-mono text-[#0f172a] dark:text-white focus:outline-none focus:border-[#00875a]"
                  />
                </div>
              </div>

              <button
                onClick={handleExecuteSandbox}
                disabled={loading}
                className="px-6 py-2.5 bg-[#00875a] hover:bg-[#00693e] text-white font-bold text-xs rounded-xl shadow-sm transition-all flex items-center gap-2"
              >
                <Play className="w-3.5 h-3.5 fill-current" />
                <span>{loading ? 'Executing...' : 'Run Test Request'}</span>
              </button>

              {response && (
                <div className="space-y-2 pt-2 border-t border-slate-100 dark:border-slate-800">
                  <span className="text-xs font-bold text-[#0f172a] dark:text-white block">
                    Response Output:
                  </span>
                  <pre className="p-3.5 rounded-xl bg-slate-900 text-slate-100 text-xs font-mono overflow-x-auto max-h-60 border border-slate-800">
                    {JSON.stringify(response, null, 2)}
                  </pre>
                </div>
              )}
            </div>
          </div>

          {/* Right: API Reference Quick Index */}
          <div className="lg:col-span-4 space-y-4">
            <div className="nin-card p-6 space-y-4">
              <h3 className="text-sm font-bold text-[#0f172a] dark:text-white border-b border-slate-100 dark:border-slate-800 pb-3">
                Error Code Reference
              </h3>
              <div className="space-y-3 text-xs">
                <div>
                  <code className="text-rose-600 font-bold font-mono">IDENTITY_NOT_FOUND (404)</code>
                  <p className="text-slate-500 mt-0.5">The provided 11-digit NIN does not exist in the identity registry.</p>
                </div>
                <div>
                  <code className="text-amber-600 font-bold font-mono">INSUFFICIENT_BALANCE (402)</code>
                  <p className="text-slate-500 mt-0.5">User wallet balance is below the per-call fee threshold.</p>
                </div>
                <div>
                  <code className="text-purple-600 font-bold font-mono">RATE_LIMIT_EXCEEDED (429)</code>
                  <p className="text-slate-500 mt-0.5">Request throughput exceeds 120 calls/min sliding limit.</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>

      <Footer />
    </div>
  );
}
