'use client';

import React, { useState, useEffect } from 'react';
import { KeyRound, Plus, Copy, Check, Trash2, ShieldCheck, AlertCircle, Sparkles } from 'lucide-react';
import SmartAuthCard from '@/components/ui/smartauth/SmartAuthCard';
import SmartAuthButton from '@/components/ui/smartauth/SmartAuthButton';
import SmartAuthBadge from '@/components/ui/smartauth/SmartAuthBadge';
import SmartAuthModal from '@/components/ui/smartauth/SmartAuthModal';

export default function ApiKeysPage() {
  const [keys, setKeys] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [createModalOpen, setCreateModalOpen] = useState(false);
  const [newKeyName, setNewKeyName] = useState('');
  const [newKeyEnv, setNewKeyEnv] = useState<'SANDBOX' | 'PRODUCTION'>('SANDBOX');
  const [generatedKey, setGeneratedKey] = useState<string | null>(null);
  const [copiedKey, setCopiedKey] = useState(false);
  const [creating, setCreating] = useState(false);

  const fetchKeys = async () => {
    try {
      const res = await fetch('/api/v1/keys');
      const data = await res.json();
      if (data.success) {
        setKeys(data.data.keys || []);
      }
    } catch {}
    finally {
      setLoading(false);
    }
  };

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

  const handleCreateKey = async (e: React.FormEvent) => {
    e.preventDefault();
    setCreating(true);
    try {
      const res = await fetch('/api/v1/keys', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: newKeyName, environment: newKeyEnv }),
      });
      const data = await res.json();
      if (data.success) {
        setGeneratedKey(data.data.apiKey);
        await fetchKeys();
      }
    } catch {}
    finally {
      setCreating(false);
    }
  };

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

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

  return (
    <div className="space-y-7 animate-in fade-in duration-150">
      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-extrabold text-slate-900 tracking-tight">API Cryptographic Keys</h1>
          <p className="text-xs text-slate-500 mt-1">
            Generate and manage secret keys for authenticating REST API requests to SmartAuth.
          </p>
        </div>
        <SmartAuthButton
          variant="primary"
          size="md"
          icon={Plus}
          onClick={() => {
            setGeneratedKey(null);
            setNewKeyName('');
            setCreateModalOpen(true);
          }}
        >
          Generate New API Key
        </SmartAuthButton>
      </div>

      {/* Security Best Practice Notice */}
      <div className="p-5 rounded-2xl bg-emerald-50/70 border border-emerald-200/80 text-emerald-950 flex items-start gap-3">
        <ShieldCheck className="w-5 h-5 text-emerald-700 shrink-0 mt-0.5" />
        <div className="text-xs space-y-1">
          <span className="font-bold">Cryptographic Key Security Standard:</span>
          <p className="text-emerald-900/80">
            SmartAuth hashes your secret keys using SHA-256 upon generation. Full secret keys are displayed only once upon creation and cannot be retrieved later.
          </p>
        </div>
      </div>

      {/* Keys Table Card */}
      <SmartAuthCard
        title="Active API Keys"
        subtitle="Manage authorization tokens for sandbox and production environments."
        headerIcon={KeyRound}
      >
        {keys.length > 0 ? (
          <div className="overflow-x-auto">
            <table className="w-full text-left text-xs">
              <thead>
                <tr className="border-b border-slate-100 text-slate-500 font-mono">
                  <th className="pb-3 font-semibold">Key Name</th>
                  <th className="pb-3 font-semibold">Key Prefix</th>
                  <th className="pb-3 font-semibold">Environment</th>
                  <th className="pb-3 font-semibold">Status</th>
                  <th className="pb-3 font-semibold">Created Date</th>
                  <th className="pb-3 font-semibold text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {keys.map((k) => (
                  <tr key={k.id} className="hover:bg-slate-50 transition-colors">
                    <td className="py-3.5 font-bold text-slate-900">{k.name}</td>
                    <td className="py-3.5 font-mono text-slate-600 bg-slate-100 px-2 py-1 rounded inline-block my-2">
                      {k.keyPrefix}••••••••
                    </td>
                    <td className="py-3.5">
                      <SmartAuthBadge variant={k.environment === 'PRODUCTION' ? 'warning' : 'neutral'} size="sm">
                        {k.environment}
                      </SmartAuthBadge>
                    </td>
                    <td className="py-3.5">
                      <SmartAuthBadge variant={k.status === 'ACTIVE' ? 'success' : 'error'} size="sm">
                        {k.status}
                      </SmartAuthBadge>
                    </td>
                    <td className="py-3.5 font-mono text-slate-500">{new Date(k.createdAt).toLocaleDateString()}</td>
                    <td className="py-3.5 text-right">
                      {k.status === 'ACTIVE' && (
                        <button
                          onClick={() => handleRevokeKey(k.id)}
                          className="px-2.5 py-1 text-rose-600 hover:text-rose-800 hover:bg-rose-50 rounded-lg font-semibold transition-colors inline-flex items-center gap-1"
                        >
                          <Trash2 className="w-3.5 h-3.5" />
                          <span>Revoke</span>
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <p className="text-xs text-slate-400 font-mono text-center py-6">No API keys generated yet.</p>
        )}
      </SmartAuthCard>

      {/* Key Generation Modal */}
      <SmartAuthModal
        isOpen={createModalOpen}
        onClose={() => setCreateModalOpen(false)}
        title={generatedKey ? 'API Key Generated' : 'Generate New API Key'}
        subtitle={
          generatedKey
            ? 'Please copy your secret key immediately. You will not be able to see it again.'
            : 'Enter a label and environment for your key.'
        }
      >
        {generatedKey ? (
          <div className="space-y-4">
            <div className="p-4 rounded-xl bg-slate-900 text-emerald-400 font-mono text-xs break-all border border-slate-800 flex items-center justify-between gap-2">
              <span>{generatedKey}</span>
              <button
                onClick={handleCopyGenerated}
                className="px-3 py-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white font-bold inline-flex items-center gap-1 shrink-0 transition-colors"
              >
                {copiedKey ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
                <span>{copiedKey ? 'Copied' : 'Copy'}</span>
              </button>
            </div>
            <div className="flex justify-end">
              <SmartAuthButton variant="primary" size="md" onClick={() => setCreateModalOpen(false)}>
                Done
              </SmartAuthButton>
            </div>
          </div>
        ) : (
          <form onSubmit={handleCreateKey} className="space-y-4">
            <div className="space-y-1.5">
              <label className="text-xs font-bold text-slate-700">Key Name</label>
              <input
                type="text"
                required
                placeholder="e.g. Production Backend Service"
                value={newKeyName}
                onChange={(e) => setNewKeyName(e.target.value)}
                className="w-full px-4 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-emerald-500/20"
              />
            </div>

            <div className="space-y-1.5">
              <label className="text-xs font-bold text-slate-700">Environment</label>
              <select
                value={newKeyEnv}
                onChange={(e) => setNewKeyEnv(e.target.value as any)}
                className="w-full px-4 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-emerald-500/20 bg-white"
              >
                <option value="SANDBOX">SANDBOX (Test simulated records)</option>
                <option value="PRODUCTION">PRODUCTION (Live NIMC & BVN registry)</option>
              </select>
            </div>

            <div className="pt-2 flex justify-end gap-2">
              <SmartAuthButton variant="outline" size="md" onClick={() => setCreateModalOpen(false)}>
                Cancel
              </SmartAuthButton>
              <SmartAuthButton type="submit" variant="primary" size="md" loading={creating}>
                Generate Key
              </SmartAuthButton>
            </div>
          </form>
        )}
      </SmartAuthModal>
    </div>
  );
}
