import { useState } from 'react';
import useSWR, { mutate } from 'swr';
import { api, type ApiKey } from '../lib/api';

export default function Keys() {
  const { data: keys } = useSWR('keys', api.listKeys);
  const [newKeyName, setNewKeyName] = useState('');
  const [createdKey, setCreatedKey] = useState<string | null>(null);

  const create = async () => {
    if (!newKeyName.trim()) return;
    const result = await api.createKey(newKeyName.trim());
    setCreatedKey(result.key);
    setNewKeyName('');
    mutate('keys');
  };

  const revoke = async (id: string, name: string) => {
    if (!confirm(`Revoke key "${name}"? This cannot be undone.`)) return;
    await api.revokeKey(id);
    mutate('keys');
  };

  return (
    <div className="space-y-6">
      <h2 className="text-xl font-semibold">API Keys</h2>

      {/* Create key */}
      <div className="bg-dd0c-surface border border-dd0c-border rounded-lg p-4">
        <h3 className="text-sm font-medium text-dd0c-muted mb-3">Create New Key</h3>
        <div className="flex gap-2">
          <input
            value={newKeyName}
            onChange={(e) => setNewKeyName(e.target.value)}
            placeholder="Key name (e.g. Production, Staging)"
            className="flex-1 bg-dd0c-bg border border-dd0c-border rounded px-3 py-1.5 text-sm"
            onKeyDown={(e) => e.key === 'Enter' && create()}
          />
          <button
            onClick={create}
            className="px-4 py-1.5 bg-dd0c-primary text-white text-sm rounded-md hover:bg-dd0c-primary/80"
          >
            Generate
          </button>
        </div>

        {createdKey && (
          <div className="mt-3 p-3 bg-dd0c-success/10 border border-dd0c-success/30 rounded-md">
            <p className="text-xs text-dd0c-success mb-1">Copy this key now — it won't be shown again.</p>
            <code className="text-sm font-mono text-dd0c-text break-all select-all">{createdKey}</code>
            <button
              onClick={() => { navigator.clipboard.writeText(createdKey); }}
              className="ml-2 text-xs text-dd0c-muted hover:text-dd0c-text"
            >
              📋 Copy
            </button>
          </div>
        )}
      </div>

      {/* Keys table */}
      <div className="bg-dd0c-surface border border-dd0c-border rounded-lg overflow-hidden">
        <table className="w-full text-sm" role="table">
          <thead>
            <tr className="text-dd0c-muted text-xs uppercase tracking-wide border-b border-dd0c-border">
              <th className="text-left py-2 px-3">Name</th>
              <th className="text-left py-2 px-3">Key</th>
              <th className="text-left py-2 px-3">Scopes</th>
              <th className="text-left py-2 px-3">Last Used</th>
              <th className="text-left py-2 px-3">Created</th>
              <th className="text-right py-2 px-3">Actions</th>
            </tr>
          </thead>
          <tbody>
            {(keys ?? []).map((key) => (
              <tr key={key.id} className="border-b border-dd0c-border/50 hover:bg-dd0c-border/20">
                <td className="py-2 px-3">{key.name}</td>
                <td className="py-2 px-3 font-mono text-dd0c-muted">{key.key_prefix}••••••••</td>
                <td className="py-2 px-3">
                  {key.scopes.map((s) => (
                    <span key={s} className="px-1.5 py-0.5 rounded text-xs bg-dd0c-border text-dd0c-muted mr-1">
                      {s}
                    </span>
                  ))}
                </td>
                <td className="py-2 px-3 text-dd0c-muted text-xs">
                  {key.last_used_at ? new Date(key.last_used_at).toLocaleDateString() : 'Never'}
                </td>
                <td className="py-2 px-3 text-dd0c-muted text-xs">
                  {new Date(key.created_at).toLocaleDateString()}
                </td>
                <td className="py-2 px-3 text-right">
                  <button
                    onClick={() => revoke(key.id, key.name)}
                    className="text-dd0c-danger/60 hover:text-dd0c-danger text-xs"
                  >
                    Revoke
                  </button>
                </td>
              </tr>
            ))}
            {(keys ?? []).length === 0 && (
              <tr>
                <td colSpan={6} className="py-8 text-center text-dd0c-muted">
                  No API keys. Generate one to start routing.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* Usage instructions */}
      <div className="bg-dd0c-surface border border-dd0c-border rounded-lg p-4">
        <h3 className="text-sm font-medium text-dd0c-muted mb-2">Quick Start</h3>
        <pre className="text-xs font-mono text-dd0c-text bg-dd0c-bg p-3 rounded overflow-x-auto">
{`# Replace your OpenAI base URL
export OPENAI_BASE_URL=https://route.dd0c.dev/v1
export OPENAI_API_KEY=dd0c_your_key_here

# Your existing code works unchanged
from openai import OpenAI
client = OpenAI()  # Uses dd0c proxy automatically`}
        </pre>
      </div>
    </div>
  );
}
