'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import NINAuthSidebar from '@/components/dashboard/NINAuthSidebar';
import NINAuthHeader from '@/components/dashboard/NINAuthHeader';
import {
  Code2,
  Copy,
  Check,
  Eye,
  EyeOff,
  Download,
  AlertCircle,
  X,
  Plus,
  Trash2,
  ShieldCheck,
  Zap,
  Server,
} from 'lucide-react';

export default function DevelopersPage() {
  const [user, setUser] = useState<any>(null);
  const [apiKeys, setApiKeys] = useState<any[]>([]);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [activeTab, setActiveTab] = useState<'KEY_MANAGEMENT' | 'API_CREDENTIALS' | 'API_STATUS'>('KEY_MANAGEMENT');
  const [showAlert, setShowAlert] = useState(true);

  // Key visibility & copy states
  const [copiedPublicKey, setCopiedPublicKey] = useState(false);
  const [copiedPrivateKey, setCopiedPrivateKey] = useState(false);
  const [showPublicKey, setShowPublicKey] = useState(true);
  const [showPrivateKey, setShowPrivateKey] = useState(false);

  // New API Key Modal
  const [newKeyName, setNewKeyName] = useState('');
  const [keyEnv, setKeyEnv] = useState('SANDBOX');
  const [creatingKey, setCreatingKey] = useState(false);
  const [revealedKey, setRevealedKey] = useState<string | null>(null);

  // Sample RSA 2048-bit keys for secure encryption
  const samplePublicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzbHu3ayPuty13trQ52xT
QoHkOVkqK3+67J/7eEC8/aVHa
as0yvR2w4Palwjr+CLd95K0xBel09+M1FseL89yOYE/7xq
llphliLDPPrjNq2e1Y+CLU+wS17dO+wV0p+oG9w15f4HtihQFeMug
/9mWFnzVf5dw62zV2Q1Zc5h3s0199J58d6e32qVJ2jE0m2wJd1v0d6Tf8s
EhkFnj5jlZAzsURw77eG6w+sU1J0hZp97+w3SNed+rhnqM+RagzgN5r7du0sVRqge
HwIDAQAB
-----END PUBLIC KEY-----`;

  const samplePrivateKey = `-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAzbHu3ayPuty13trQ52xTQoHkOVkqK3+67J/7eEC8/aVHaas0
yvR2w4Palwjr+CLd95K0xBel09+M1FseL89yOYE/7xqllphliLDPPrjNq2e1Y+CL
U+wS17dO+wV0p+oG9w15f4HtihQFeMug/9mWFnzVf5dw62zV2Q1Zc5h3s0199J58
d6e32qVJ2jE0m2wJd1v0d6Tf8sEhkFnj5jlZAzsURw77eG6w+sU1J0hZp97+w3SN
ed+rhnqM+RagzgN5r7du0sVRqgeHwIDAQABAoIBAGX7v8+3Qx2/9wF8v+...
-----END RSA PRIVATE KEY-----`;

  const fetchKeys = async () => {
    try {
      const [accRes, keysRes] = await Promise.all([
        fetch('/api/v1/account'),
        fetch('/api/v1/keys'),
      ]);
      const accData = await accRes.json();
      const keysData = await keysRes.json();
      if (accData.success) setUser(accData.data.user);
      if (keysData.success) setApiKeys(keysData.data || []);
    } catch {}
  };

  useEffect(() => {
    fetchKeys();
  }, []);

  const handleCopyPublic = () => {
    navigator.clipboard.writeText(samplePublicKey);
    setCopiedPublicKey(true);
    setTimeout(() => setCopiedPublicKey(false), 2000);
  };

  const handleCopyPrivate = () => {
    navigator.clipboard.writeText(samplePrivateKey);
    setCopiedPrivateKey(true);
    setTimeout(() => setCopiedPrivateKey(false), 2000);
  };

  const handleDownloadKey = (keyContent: string, filename: string) => {
    const blob = new Blob([keyContent], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleCreateApiKey = async (e: React.FormEvent) => {
    e.preventDefault();
    setCreatingKey(true);
    try {
      const res = await fetch('/api/v1/keys', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: newKeyName || 'Default Secret Key', environment: keyEnv }),
      });
      const data = await res.json();
      if (data.success) {
        setRevealedKey(data.data.fullKey);
        setNewKeyName('');
        fetchKeys();
      }
    } catch {}
    finally {
      setCreatingKey(false);
    }
  };

  const handleRevokeKey = async (id: string) => {
    if (confirm('Are you sure you want to revoke this secret key? This action is immediate and cannot be undone.')) {
      await fetch(`/api/v1/keys/${id}`, { method: 'DELETE' });
      fetchKeys();
    }
  };

  return (
    <div className="flex min-h-screen bg-[#f7f9fa] dark:bg-[#070b14] text-[#1e293b] dark:text-slate-100 font-sans">
      <NINAuthSidebar
        collapsed={sidebarCollapsed}
        onToggleCollapse={() => setSidebarCollapsed(!sidebarCollapsed)}
        userRole={user?.role}
      />

      <div className="flex-1 flex flex-col min-w-0">
        <NINAuthHeader
          user={user}
          onToggleSidebar={() => setSidebarCollapsed(!sidebarCollapsed)}
        />

        <main className="flex-1 p-6 sm:p-8 space-y-6 overflow-y-auto max-w-7xl">
          {/* Top Sub-Tabs & Action Button matching Screenshot 5 */}
          <div className="flex flex-wrap items-center justify-between gap-4">
            {/* 3 Sub-tabs matching Screenshot 5 */}
            <div className="flex flex-wrap items-center gap-2">
              <button
                type="button"
                onClick={() => setActiveTab('KEY_MANAGEMENT')}
                className={`px-5 py-2.5 rounded-xl text-xs font-mono font-bold transition-all ${
                  activeTab === 'KEY_MANAGEMENT'
                    ? 'bg-[#eef2ff] dark:bg-indigo-950/60 text-[#4338ca] dark:text-indigo-300 shadow-sm border border-indigo-200 dark:border-indigo-800'
                    : 'bg-white dark:bg-slate-900 border border-[#e2e8f0] dark:border-slate-800 text-[#64748b] dark:text-slate-400 hover:bg-slate-50'
                }`}
              >
                KEY MANAGEMENT
              </button>

              <button
                type="button"
                onClick={() => setActiveTab('API_CREDENTIALS')}
                className={`px-5 py-2.5 rounded-xl text-xs font-mono font-bold transition-all ${
                  activeTab === 'API_CREDENTIALS'
                    ? 'bg-[#eef2ff] dark:bg-indigo-950/60 text-[#4338ca] dark:text-indigo-300 shadow-sm border border-indigo-200 dark:border-indigo-800'
                    : 'bg-white dark:bg-slate-900 border border-[#e2e8f0] dark:border-slate-800 text-[#64748b] dark:text-slate-400 hover:bg-slate-50'
                }`}
              >
                API CREDENTIALS
              </button>

              <button
                type="button"
                onClick={() => setActiveTab('API_STATUS')}
                className={`px-5 py-2.5 rounded-xl text-xs font-mono font-bold transition-all ${
                  activeTab === 'API_STATUS'
                    ? 'bg-[#eef2ff] dark:bg-indigo-950/60 text-[#4338ca] dark:text-indigo-300 shadow-sm border border-indigo-200 dark:border-indigo-800'
                    : 'bg-white dark:bg-slate-900 border border-[#e2e8f0] dark:border-slate-800 text-[#64748b] dark:text-slate-400 hover:bg-slate-50'
                }`}
              >
                API STATUS
              </button>
            </div>

            {/* API Documentation pill button matching Screenshot 5 */}
            <Link
              href="/docs"
              className="inline-flex items-center gap-2 px-6 py-2.5 bg-[#00875a] hover:bg-[#00693e] text-white font-semibold text-xs rounded-full shadow-sm transition-all"
            >
              API Documentation
            </Link>
          </div>

          {/* Alert Notification matching Screenshot 5 */}
          {showAlert && (
            <div className="bg-[#fefce8] dark:bg-amber-950/30 border border-[#fde047] dark:border-amber-700/50 rounded-2xl p-5 space-y-2 relative shadow-sm">
              <div className="flex items-start justify-between">
                <div className="flex items-center gap-2.5">
                  <div className="w-5 h-5 rounded-full bg-[#eab308] text-white font-bold text-xs flex items-center justify-center shrink-0">
                    !
                  </div>
                  <h4 className="text-xs sm:text-sm font-bold text-[#854d0e] dark:text-amber-200">
                    Manage your RSA public and private keys for secure NIN authentication
                  </h4>
                </div>
                <button
                  onClick={() => setShowAlert(false)}
                  className="text-[#a16207] hover:text-[#713f12] dark:text-amber-300 p-0.5"
                >
                  <X className="w-4 h-4" />
                </button>
              </div>

              <p className="text-xs text-[#a16207] dark:text-amber-300/90 leading-relaxed pl-7">
                Here, you can generate copy or download the cryptographic keys used to encrypt and decrypt NIN verification requests. Ensure your private key is stored securely and never shared.
              </p>
            </div>
          )}

          {/* TAB 1: KEY MANAGEMENT (RSA Keys matching Screenshot 5) */}
          {activeTab === 'KEY_MANAGEMENT' && (
            <div className="space-y-6">
              {/* Public Key Card matching Screenshot 5 */}
              <div className="nin-card p-6 sm:p-7 space-y-4">
                <div className="flex items-center justify-between border-b border-slate-100 dark:border-slate-800/80 pb-3">
                  <span className="text-[11.5px] font-mono font-semibold tracking-wider text-[#64748b] dark:text-slate-400 uppercase">
                    PUBLIC KEY
                  </span>

                  <div className="flex items-center gap-2">
                    {/* Copy Button */}
                    <button
                      onClick={handleCopyPublic}
                      className="p-2 rounded-xl bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 text-[#475569] dark:text-slate-300 transition-colors"
                      title="Copy Public Key"
                    >
                      {copiedPublicKey ? <Check className="w-4 h-4 text-emerald-600" /> : <Copy className="w-4 h-4" />}
                    </button>

                    {/* View/Hide Button */}
                    <button
                      onClick={() => setShowPublicKey(!showPublicKey)}
                      className="p-2 rounded-xl bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 text-[#475569] dark:text-slate-300 transition-colors"
                      title={showPublicKey ? 'Hide' : 'View'}
                    >
                      {showPublicKey ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                    </button>

                    {/* Download Button */}
                    <button
                      onClick={() => handleDownloadKey(samplePublicKey, 'smartauth-public-key.pem')}
                      className="flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl border border-[#e2e8f0] dark:border-slate-700 bg-white dark:bg-slate-900 hover:bg-slate-50 text-xs font-medium text-[#0f172a] dark:text-white transition-colors shadow-sm"
                    >
                      <span>Download</span>
                      <Download className="w-3.5 h-3.5" />
                    </button>
                  </div>
                </div>

                {/* Key Monospace Box */}
                <div className="bg-[#f8fafc] dark:bg-slate-900/90 rounded-xl p-4 border border-[#e2e8f0] dark:border-slate-800 font-mono text-xs text-[#334155] dark:text-slate-200 overflow-x-auto leading-relaxed">
                  {showPublicKey ? (
                    <pre>{samplePublicKey}</pre>
                  ) : (
                    <div className="py-4 text-center text-slate-400 font-sans">
                      •••••••• Public key hidden. Click the eye icon to reveal. ••••••••
                    </div>
                  )}
                </div>
              </div>

              {/* Private Key Card */}
              <div className="nin-card p-6 sm:p-7 space-y-4">
                <div className="flex items-center justify-between border-b border-slate-100 dark:border-slate-800/80 pb-3">
                  <div className="flex items-center gap-2">
                    <span className="text-[11.5px] font-mono font-semibold tracking-wider text-[#64748b] dark:text-slate-400 uppercase">
                      PRIVATE KEY (CLIENT DECRYPTION SECRET)
                    </span>
                    <span className="px-2 py-0.5 rounded bg-rose-100 text-rose-700 dark:bg-rose-950/60 dark:text-rose-300 text-[10px] font-bold">
                      CONFIDENTIAL
                    </span>
                  </div>

                  <div className="flex items-center gap-2">
                    <button
                      onClick={handleCopyPrivate}
                      className="p-2 rounded-xl bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 text-[#475569] dark:text-slate-300 transition-colors"
                      title="Copy Private Key"
                    >
                      {copiedPrivateKey ? <Check className="w-4 h-4 text-emerald-600" /> : <Copy className="w-4 h-4" />}
                    </button>

                    <button
                      onClick={() => setShowPrivateKey(!showPrivateKey)}
                      className="p-2 rounded-xl bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 text-[#475569] dark:text-slate-300 transition-colors"
                      title={showPrivateKey ? 'Hide' : 'View'}
                    >
                      {showPrivateKey ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                    </button>

                    <button
                      onClick={() => handleDownloadKey(samplePrivateKey, 'smartauth-private-key.pem')}
                      className="flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl border border-[#e2e8f0] dark:border-slate-700 bg-white dark:bg-slate-900 hover:bg-slate-50 text-xs font-medium text-[#0f172a] dark:text-white transition-colors shadow-sm"
                    >
                      <span>Download</span>
                      <Download className="w-3.5 h-3.5" />
                    </button>
                  </div>
                </div>

                <div className="bg-[#f8fafc] dark:bg-slate-900/90 rounded-xl p-4 border border-[#e2e8f0] dark:border-slate-800 font-mono text-xs text-[#334155] dark:text-slate-200 overflow-x-auto leading-relaxed">
                  {showPrivateKey ? (
                    <pre>{samplePrivateKey}</pre>
                  ) : (
                    <div className="py-4 text-center text-slate-400 font-sans">
                      •••••••• Private key hidden for security. Click the eye icon to inspect. ••••••••
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* TAB 2: API CREDENTIALS (API Keys CRUD) */}
          {activeTab === 'API_CREDENTIALS' && (
            <div className="space-y-6">
              {/* Reveal Key Alert */}
              {revealedKey && (
                <div className="p-5 rounded-2xl bg-emerald-50 dark:bg-emerald-950/40 border border-emerald-300 dark:border-emerald-700 space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-xs font-bold text-emerald-800 dark:text-emerald-200">
                      Secret Key Generated (Copy Now — It will never be shown again!)
                    </span>
                    <button onClick={() => setRevealedKey(null)} className="text-emerald-700 p-0.5">
                      <X className="w-4 h-4" />
                    </button>
                  </div>
                  <div className="flex items-center justify-between bg-white dark:bg-slate-900 p-3 rounded-xl border border-emerald-300 dark:border-emerald-800">
                    <code className="text-xs font-mono font-bold text-[#00875a] dark:text-emerald-400 select-all">
                      {revealedKey}
                    </code>
                    <button
                      onClick={() => {
                        navigator.clipboard.writeText(revealedKey);
                        alert('API Key copied to clipboard!');
                      }}
                      className="px-3 py-1 bg-[#00875a] text-white text-xs font-bold rounded-lg ml-2"
                    >
                      Copy
                    </button>
                  </div>
                </div>
              )}

              {/* Generate New Key Form */}
              <div className="nin-card p-6 sm:p-7 space-y-4">
                <h3 className="text-sm font-bold text-[#0f172a] dark:text-white border-b border-slate-100 dark:border-slate-800/80 pb-3">
                  Generate New API Secret Key
                </h3>

                <form onSubmit={handleCreateApiKey} className="flex flex-wrap items-center gap-3">
                  <input
                    type="text"
                    required
                    value={newKeyName}
                    onChange={(e) => setNewKeyName(e.target.value)}
                    placeholder="e.g. Production Backend, Android App"
                    className="flex-1 min-w-[240px] bg-[#f8fafc] dark:bg-slate-900 border border-[#e2e8f0] dark:border-slate-700 rounded-xl px-3.5 py-2.5 text-xs text-[#0f172a] dark:text-white focus:outline-none focus:border-[#00875a]"
                  />

                  <select
                    value={keyEnv}
                    onChange={(e) => setKeyEnv(e.target.value)}
                    className="bg-[#f8fafc] dark:bg-slate-900 border border-[#e2e8f0] dark:border-slate-700 rounded-xl px-3.5 py-2.5 text-xs text-[#0f172a] dark:text-white font-mono"
                  >
                    <option value="SANDBOX">SANDBOX (sk_test_...)</option>
                    <option value="PRODUCTION">PRODUCTION (sk_live_...)</option>
                  </select>

                  <button
                    type="submit"
                    disabled={creatingKey}
                    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-1.5 disabled:opacity-50"
                  >
                    <Plus className="w-4 h-4" />
                    <span>Create Key</span>
                  </button>
                </form>
              </div>

              {/* Active Keys Table */}
              <div className="nin-card p-6 sm:p-7 space-y-4">
                <span className="text-[11.5px] font-mono font-semibold tracking-wider text-[#64748b] dark:text-slate-400 uppercase block">
                  ACTIVE API CREDENTIALS
                </span>

                <div className="overflow-x-auto">
                  <table className="w-full text-left text-xs font-mono">
                    <thead>
                      <tr className="border-b border-[#cbd5e1] dark:border-slate-800 text-[#475569] dark:text-slate-400 text-[11px]">
                        <th className="py-3 px-3">KEY NAME</th>
                        <th className="py-3 px-3">KEY PREFIX</th>
                        <th className="py-3 px-3">ENVIRONMENT</th>
                        <th className="py-3 px-3">CREATED</th>
                        <th className="py-3 px-3 text-right">ACTION</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100 dark:divide-slate-800/60 text-slate-600 dark:text-slate-300">
                      {apiKeys.map((key) => (
                        <tr key={key.id} className="hover:bg-slate-50 dark:hover:bg-slate-900/40">
                          <td className="py-3 px-3 font-sans font-semibold text-[#0f172a] dark:text-white">
                            {key.name}
                          </td>
                          <td className="py-3 px-3 font-bold text-[#00875a] dark:text-emerald-400">
                            {key.keyPrefix}••••••••••••
                          </td>
                          <td className="py-3 px-3">
                            <span
                              className={`px-2 py-0.5 rounded text-[10px] font-bold ${
                                key.environment === 'PRODUCTION'
                                  ? 'bg-amber-100 text-amber-800 dark:bg-amber-950/60 dark:text-amber-300'
                                  : 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950/60 dark:text-emerald-300'
                              }`}
                            >
                              {key.environment}
                            </span>
                          </td>
                          <td className="py-3 px-3 text-slate-500">
                            {new Date(key.createdAt).toLocaleDateString()}
                          </td>
                          <td className="py-3 px-3 text-right">
                            <button
                              onClick={() => handleRevokeKey(key.id)}
                              className="px-2.5 py-1 text-[#e11d48] hover:bg-rose-50 dark:hover:bg-rose-950/30 rounded-lg text-xs font-semibold inline-flex items-center gap-1 transition-colors"
                            >
                              <Trash2 className="w-3.5 h-3.5" />
                              Revoke
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}

          {/* TAB 3: API STATUS */}
          {activeTab === 'API_STATUS' && (
            <div className="nin-card p-6 sm:p-7 space-y-6">
              <span className="text-[11.5px] font-mono font-semibold tracking-wider text-[#64748b] dark:text-slate-400 uppercase block">
                GATEWAY & IDENTITY REGISTRY HEALTH
              </span>

              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <div className="p-5 rounded-2xl bg-[#f8fafc] dark:bg-slate-900/80 border border-[#e2e8f0] dark:border-slate-800 space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-xs font-semibold text-slate-500">Gateway Status</span>
                    <span className="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span>
                  </div>
                  <div className="text-xl font-bold text-emerald-600">Operational (100%)</div>
                </div>

                <div className="p-5 rounded-2xl bg-[#f8fafc] dark:bg-slate-900/80 border border-[#e2e8f0] dark:border-slate-800 space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-xs font-semibold text-slate-500">Avg Verification Latency</span>
                    <Zap className="w-4 h-4 text-[#00875a]" />
                  </div>
                  <div className="text-xl font-bold text-[#0f172a] dark:text-white font-mono">248 ms</div>
                </div>

                <div className="p-5 rounded-2xl bg-[#f8fafc] dark:bg-slate-900/80 border border-[#e2e8f0] dark:border-slate-800 space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-xs font-semibold text-slate-500">Operating Mode</span>
                    <Server className="w-4 h-4 text-emerald-600" />
                  </div>
                  <div className="text-xl font-bold text-[#00875a] font-mono">SANDBOX</div>
                </div>
              </div>
            </div>
          )}
        </main>
      </div>
    </div>
  );
}
