'use client';

import React, { useState, useEffect } from 'react';
import Sidebar from '@/components/dashboard/Sidebar';
import Header from '@/components/dashboard/Header';
import {
  Key,
  Plus,
  Trash2,
  Copy,
  Check,
  CheckCircle2,
  AlertTriangle,
  RefreshCw,
  X,
  ShieldCheck,
  Clock,
} from 'lucide-react';

export default function ApiKeysPage() {
  const [user, setUser] = useState<any>(null);
  const [wallet, setWallet] = useState<any>(null);
  const [keys, setKeys] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  // New Key Generation Modal
  const [modalOpen, setModalOpen] = useState(false);
  const [keyName, setKeyName] = useState('My Sandbox App');
  const [environment, setEnvironment] = useState<'SANDBOX' | 'PRODUCTION'>('SANDBOX');
  const [rateLimit, setRateLimit] = useState('120');
  const [generating, setGenerating] = useState(false);

  // Newly generated key display
  const [newlyCreatedKey, setNewlyCreatedKey] = useState<string | null>(null);
  const [copiedKey, setCopiedKey] = useState(false);

  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);
        setWallet(accData.data.wallet);
      }
      if (keysData.success) {
        setKeys(keysData.data || []);
      }
    } catch {}
    finally {
      setLoading(false);
    }
  };

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

  const handleGenerateKey = async (e: React.FormEvent) => {
    e.preventDefault();
    setGenerating(true);

    try {
      const res = await fetch('/api/v1/keys', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: keyName,
          environment,
          rateLimit: parseInt(rateLimit, 10),
        }),
      });
      const data = await res.json();
      if (data.success) {
        setNewlyCreatedKey(data.data.fullKey);
        fetchKeys();
      }
    } catch {
    } finally {
      setGenerating(false);
    }
  };

  const handleRevokeKey = async (id: string) => {
    if (!confirm('Are you sure you want to revoke this API key? This action is permanent.')) return;

    try {
      const res = await fetch(`/api/v1/keys/${id}`, { method: 'DELETE' });
      const data = await res.json();
      if (data.success) {
        fetchKeys();
      }
    } catch {}
  };

  const handleCopy = () => {
    if (newlyCreatedKey) {
      navigator.clipboard.writeText(newlyCreatedKey);
      setCopiedKey(true);
      setTimeout(() => setCopiedKey(false), 2000);
    }
  };

  return (
    <div className="flex min-h-screen bg-[#070b14] text-slate-100">
      <Sidebar userRole={user?.role} />

      <div className="flex-1 flex flex-col min-w-0">
        <Header user={user} walletBalance={wallet?.balance || 0} onRefreshWallet={fetchKeys} />

        <main className="flex-1 p-6 space-y-6 overflow-y-auto max-w-7xl">
          {/* Top Title & Action */}
          <div className="flex flex-wrap items-center justify-between gap-4">
            <div>
              <h1 className="text-xl font-bold text-white flex items-center gap-2">
                <Key className="w-5 h-5 text-emerald-400" />
                API Keys Management
              </h1>
              <p className="text-xs text-slate-400 mt-0.5">
                Generate and manage secret keys used to authenticate REST API calls.
              </p>
            </div>

            <button
              onClick={() => {
                setNewlyCreatedKey(null);
                setModalOpen(true);
              }}
              className="px-4 py-2 bg-emerald-400 hover:bg-emerald-300 text-slate-900 font-bold text-xs rounded-xl shadow-md shadow-emerald-500/20 transition-all flex items-center gap-2"
            >
              <Plus className="w-4 h-4" />
              Generate New API Key
            </button>
          </div>

          {/* Security Notice */}
          <div className="p-4 rounded-2xl bg-slate-900/80 border border-slate-800 flex items-start gap-3 text-xs text-slate-300">
            <ShieldCheck className="w-5 h-5 text-emerald-400 shrink-0 mt-0.5" />
            <div className="space-y-1">
              <span className="font-bold text-white">SHA-256 Key Hashing & Isolation</span>
              <p className="text-slate-400 leading-relaxed">
                For security, full secret API keys are only revealed once upon creation. We store only cryptographic SHA-256 hashes and key prefixes in our database.
              </p>
            </div>
          </div>

          {/* API Keys Table */}
          <div className="glass-panel rounded-2xl p-6 border border-slate-800 space-y-4">
            <div className="overflow-x-auto">
              <table className="w-full text-left text-xs font-mono">
                <thead>
                  <tr className="border-b border-slate-800 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">Rate Limit</th>
                    <th className="py-3 px-3">Last Used</th>
                    <th className="py-3 px-3">Status</th>
                    <th className="py-3 px-3 text-right">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-800/60 text-slate-300">
                  {keys.length > 0 ? (
                    keys.map((k) => (
                      <tr key={k.id} className="hover:bg-slate-900/40 transition-colors">
                        <td className="py-3 px-3 font-sans font-semibold text-white">{k.name}</td>
                        <td className="py-3 px-3 font-mono text-emerald-400">{k.keyPrefix}...</td>
                        <td className="py-3 px-3">
                          <span
                            className={`px-2 py-0.5 rounded text-[10px] font-bold ${
                              k.environment === 'PRODUCTION'
                                ? 'bg-amber-500/20 text-amber-300 border border-amber-500/30'
                                : 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
                            }`}
                          >
                            {k.environment}
                          </span>
                        </td>
                        <td className="py-3 px-3">{k.rateLimit} req/min</td>
                        <td className="py-3 px-3 text-slate-400 font-sans">
                          {k.lastUsedAt ? new Date(k.lastUsedAt).toLocaleDateString() : 'Never'}
                        </td>
                        <td className="py-3 px-3">
                          <span
                            className={`px-2 py-0.5 rounded-full text-[10px] font-bold ${
                              k.status === 'ACTIVE'
                                ? 'bg-emerald-500/20 text-emerald-300'
                                : 'bg-rose-500/20 text-rose-300'
                            }`}
                          >
                            {k.status}
                          </span>
                        </td>
                        <td className="py-3 px-3 text-right">
                          {k.status === 'ACTIVE' && (
                            <button
                              onClick={() => handleRevokeKey(k.id)}
                              className="text-slate-400 hover:text-rose-400 p-1 transition-colors"
                              title="Revoke Key"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          )}
                        </td>
                      </tr>
                    ))
                  ) : (
                    <tr>
                      <td colSpan={7} className="py-6 text-center text-slate-500 font-sans">
                        {loading ? 'Loading API keys...' : 'No API keys created yet.'}
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>

          {/* Modal for Creating New Key */}
          {modalOpen && (
            <div className="fixed inset-0 bg-black/75 backdrop-blur-sm z-50 flex items-center justify-center p-4">
              <div className="glass-panel w-full max-w-md rounded-2xl p-6 border border-slate-700 space-y-5 shadow-2xl animate-in fade-in zoom-in-95 duration-200">
                <div className="flex items-center justify-between border-b border-slate-800 pb-3">
                  <div className="flex items-center gap-2">
                    <Key className="w-5 h-5 text-emerald-400" />
                    <h3 className="text-base font-bold text-white">Generate New API Key</h3>
                  </div>
                  <button
                    onClick={() => setModalOpen(false)}
                    className="text-slate-400 hover:text-white p-1"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>

                {newlyCreatedKey ? (
                  /* Key Reveal State */
                  <div className="space-y-4">
                    <div className="p-3.5 rounded-xl bg-emerald-500/10 border border-emerald-500/30 flex items-center gap-2 text-xs text-emerald-300">
                      <CheckCircle2 className="w-4 h-4 shrink-0" />
                      <span>API key created successfully! Copy it now.</span>
                    </div>

                    <div className="space-y-2">
                      <label className="block text-[11px] font-bold text-slate-400 uppercase tracking-wider">
                        Your Secret API Key (Revealed Once)
                      </label>
                      <div className="flex items-center justify-between bg-slate-900 p-3 rounded-xl border border-slate-800 font-mono text-xs text-emerald-300">
                        <span className="truncate mr-2">{newlyCreatedKey}</span>
                        <button
                          onClick={handleCopy}
                          className="p-1 text-slate-400 hover:text-white shrink-0"
                        >
                          {copiedKey ? <Check className="w-4 h-4 text-emerald-400" /> : <Copy className="w-4 h-4" />}
                        </button>
                      </div>
                    </div>

                    <div className="p-3 rounded-xl bg-amber-500/10 border border-amber-500/20 text-xs text-amber-300">
                      Save this key in your environment variables. You will not be able to retrieve it again.
                    </div>

                    <button
                      onClick={() => setModalOpen(false)}
                      className="w-full py-2.5 bg-slate-800 hover:bg-slate-700 text-white font-bold text-xs rounded-xl transition-all"
                    >
                      Done & Close
                    </button>
                  </div>
                ) : (
                  /* Creation Form */
                  <form onSubmit={handleGenerateKey} className="space-y-4">
                    <div>
                      <label className="block text-xs font-semibold text-slate-300 mb-1.5">
                        Key Name / Identifier
                      </label>
                      <input
                        type="text"
                        required
                        value={keyName}
                        onChange={(e) => setKeyName(e.target.value)}
                        placeholder="e.g. Staging Server Key"
                        className="w-full bg-slate-900 border border-slate-700 rounded-xl px-3.5 py-2.5 text-xs text-white focus:outline-none focus:border-emerald-500"
                      />
                    </div>

                    <div>
                      <label className="block text-xs font-semibold text-slate-300 mb-1.5">
                        Environment
                      </label>
                      <select
                        value={environment}
                        onChange={(e) => setEnvironment(e.target.value as any)}
                        className="w-full bg-slate-900 border border-slate-700 rounded-xl px-3.5 py-2.5 text-xs text-white focus:outline-none focus:border-emerald-500"
                      >
                        <option value="SANDBOX">Sandbox Mode (sk_test_...)</option>
                        <option value="PRODUCTION">Production Mode (sk_live_...)</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-xs font-semibold text-slate-300 mb-1.5">
                        Rate Limit (Requests / minute)
                      </label>
                      <input
                        type="number"
                        value={rateLimit}
                        onChange={(e) => setRateLimit(e.target.value)}
                        className="w-full bg-slate-900 border border-slate-700 rounded-xl px-3.5 py-2.5 text-xs font-mono text-white focus:outline-none focus:border-emerald-500"
                      />
                    </div>

                    <div className="pt-2">
                      <button
                        type="submit"
                        disabled={generating}
                        className="w-full py-3 bg-emerald-400 hover:bg-emerald-300 text-slate-900 font-bold text-xs rounded-xl shadow-lg shadow-emerald-500/20 transition-all flex items-center justify-center gap-2 disabled:opacity-50"
                      >
                        {generating ? <RefreshCw className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
                        {generating ? 'Generating Key...' : 'Create Secret API Key'}
                      </button>
                    </div>
                  </form>
                )}
              </div>
            </div>
          )}
        </main>
      </div>
    </div>
  );
}
