'use client';

import { useState, useEffect } from 'react';
import { Key, Plus, Copy, Eye, EyeOff, Trash2, CheckCircle, Shield } from 'lucide-react';

interface ApiKey {
  id: string;
  name: string;
  prefix: string;
  createdAt: string;
  lastUsedAt: string | null;
  expiresAt: string | null;
  status: 'active' | 'revoked';
}

export default function ApiKeysPage() {
  const [keys, setKeys] = useState<ApiKey[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreate, setShowCreate] = useState(false);
  const [newKeyName, setNewKeyName] = useState('');
  const [revealedKey, setRevealedKey] = useState<string | null>(null);
  const [copiedId, setCopiedId] = useState<string | null>(null);

  useEffect(() => {
    // Demo keys for display
    setKeys([
      { id: '1', name: 'Production Key', prefix: 'df_live_7x...k9m', createdAt: new Date(Date.now() - 30 * 86400000).toISOString(), lastUsedAt: new Date(Date.now() - 3600000).toISOString(), expiresAt: null, status: 'active' },
      { id: '2', name: 'Development Key', prefix: 'df_test_3a...p2q', createdAt: new Date(Date.now() - 14 * 86400000).toISOString(), lastUsedAt: new Date(Date.now() - 86400000).toISOString(), expiresAt: null, status: 'active' },
      { id: '3', name: 'CI/CD Pipeline', prefix: 'df_ci_9f...w4r', createdAt: new Date(Date.now() - 60 * 86400000).toISOString(), lastUsedAt: null, expiresAt: new Date(Date.now() - 7 * 86400000).toISOString(), status: 'revoked' },
    ]);
    setLoading(false);
  }, []);

  const handleCopy = (prefix: string, id: string) => {
    navigator.clipboard.writeText(prefix);
    setCopiedId(id);
    setTimeout(() => setCopiedId(null), 2000);
  };

  const handleRevoke = (id: string) => {
    setKeys(prev => prev.map(k => k.id === id ? { ...k, status: 'revoked' as const } : k));
  };

  const handleCreate = () => {
    if (!newKeyName.trim()) return;
    const newKey: ApiKey = {
      id: String(Date.now()),
      name: newKeyName,
      prefix: `df_live_${Math.random().toString(36).slice(2, 5)}...${Math.random().toString(36).slice(2, 5)}`,
      createdAt: new Date().toISOString(),
      lastUsedAt: null,
      expiresAt: null,
      status: 'active',
    };
    setKeys(prev => [newKey, ...prev]);
    setNewKeyName('');
    setShowCreate(false);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-2">
            <Key className="w-6 h-6 text-amber-400" /> API Keys
          </h1>
          <p className="text-gray-400 mt-1">Manage API keys for programmatic access to The Hearth</p>
        </div>
        <button
          onClick={() => setShowCreate(true)}
          className="flex items-center gap-2 px-4 py-2 bg-sky-500/20 text-sky-400 rounded-lg hover:bg-sky-500/30 transition-colors"
        >
          <Plus className="w-4 h-4" /> Create Key
        </button>
      </div>

      {/* Security Notice */}
      <div className="flex items-start gap-3 p-4 bg-amber-500/10 border border-amber-500/20 rounded-xl">
        <Shield className="w-5 h-5 text-amber-400 mt-0.5 shrink-0" />
        <div className="text-sm text-amber-200/80">
          API keys grant full access to your The Hearth resources. Keep them secret and never expose them in client-side code.
        </div>
      </div>

      {/* Create Key Form */}
      {showCreate && (
        <div className="p-4 bg-white/5 border border-slate-700 rounded-xl space-y-3">
          <h3 className="text-white font-medium">Create New API Key</h3>
          <input
            type="text"
            value={newKeyName}
            onChange={e => setNewKeyName(e.target.value)}
            placeholder="Key name (e.g., Production, CI/CD)"
            className="w-full px-3 py-2 bg-black/30 border border-slate-700 rounded-lg text-white placeholder:text-gray-500 focus:outline-none focus:border-sky-500"
          />
          <div className="flex gap-2">
            <button onClick={handleCreate} className="px-4 py-2 bg-sky-500 text-black rounded-lg font-medium hover:bg-sky-400 transition-colors">Create</button>
            <button onClick={() => setShowCreate(false)} className="px-4 py-2 text-gray-400 hover:text-white transition-colors">Cancel</button>
          </div>
        </div>
      )}

      {/* Keys List */}
      {loading ? (
        <div className="text-center py-12 text-gray-500">Loading keys...</div>
      ) : keys.length === 0 ? (
        <div className="text-center py-16 border border-dashed border-slate-700 rounded-xl">
          <Key className="w-12 h-12 text-gray-600 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-400">No API keys</h3>
          <p className="text-gray-500 mt-1">Create an API key to get started</p>
        </div>
      ) : (
        <div className="space-y-3">
          {keys.map(key => (
            <div key={key.id} className="p-4 bg-white/5 border border-slate-700/50 rounded-xl flex items-center justify-between">
              <div className="space-y-1">
                <div className="flex items-center gap-2">
                  <span className="text-white font-medium">{key.name}</span>
                  <span className={`text-xs px-2 py-0.5 rounded-full ${key.status === 'active' ? 'text-green-400 bg-green-400/10' : 'text-gray-500 bg-gray-500/10'}`}>
                    {key.status}
                  </span>
                </div>
                <div className="flex items-center gap-4 text-sm text-gray-500">
                  <span className="font-mono">
                    {revealedKey === key.id ? key.prefix : key.prefix.replace(/[a-z0-9]/gi, '•').slice(0, 12) + '...'}
                  </span>
                  <span>Created {new Date(key.createdAt).toLocaleDateString()}</span>
                  {key.lastUsedAt && <span>Last used {new Date(key.lastUsedAt).toLocaleDateString()}</span>}
                </div>
              </div>
              <div className="flex items-center gap-2">
                <button onClick={() => setRevealedKey(revealedKey === key.id ? null : key.id)} className="p-2 text-gray-400 hover:text-white transition-colors" title="Toggle visibility">
                  {revealedKey === key.id ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
                <button onClick={() => handleCopy(key.prefix, key.id)} className="p-2 text-gray-400 hover:text-white transition-colors" title="Copy">
                  {copiedId === key.id ? <CheckCircle className="w-4 h-4 text-green-400" /> : <Copy className="w-4 h-4" />}
                </button>
                {key.status === 'active' && (
                  <button onClick={() => handleRevoke(key.id)} className="p-2 text-gray-400 hover:text-red-400 transition-colors" title="Revoke">
                    <Trash2 className="w-4 h-4" />
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
