/**
 * Developer Dashboard — API Keys & Webhooks (v0.102)
 * Manages API keys and links to Swagger docs. Webhooks at /webhooks.
 */
import React, { useState, useEffect } from 'react';
import { Card, CardContent } from '../ui/card';
import { Button } from '../ui/button';
import { EmptyState } from '../ui/empty-state';
import { SwaggerUIDoc } from './SwaggerUI';
import { CreateAPIKeyModal } from './modals/CreateAPIKeyModal';
import { ConfirmationDialog } from '../ui/confirmation-dialog';
import {
  ExternalLink,
  Key,
  Plus,
  Trash2,
  Loader2,
} from 'lucide-react';
import { developerService, type ApiKey } from '@/services/developerService';
import { useToast } from '@/components/feedback/ToastProvider';

export const DeveloperDashboardView: React.FC = () => {
  const { addToast } = useToast();
  const [keys, setKeys] = useState<ApiKey[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [revokeId, setRevokeId] = useState<string | null>(null);

  const fetchKeys = async () => {
    setLoading(true);
    try {
      const list = await developerService.listKeys();
      setKeys(list);
    } catch (e) {
      addToast('Failed to load API keys', 'error');
      setKeys([]);
    } finally {
      setLoading(false);
    }
  };

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

  const handleCreate = async (data: {
    name: string;
    scopes: string[];
  }): Promise<{ key?: string; id: string; name: string; prefix: string }> => {
    const created = await developerService.createKey(data);
    await fetchKeys();
    return {
      key: created.key,
      id: created.id,
      name: created.name,
      prefix: created.prefix,
    };
  };

  const handleRevoke = async (id: string) => {
    try {
      await developerService.deleteKey(id);
      await fetchKeys();
      addToast('API key revoked', 'success');
    } catch {
      addToast('Failed to revoke API key', 'error');
    } finally {
      setRevokeId(null);
    }
  };

  return (
    <div className="space-y-8 animate-fadeIn pb-20">
      <div className="flex flex-col md:flex-row justify-between items-end gap-4 border-b border-border/50 pb-6">
        <div>
          <h1 className="text-3xl font-heading font-bold text-foreground mb-2">
            DEVELOPER PORTAL
          </h1>
          <p className="text-muted-foreground font-mono text-sm">
            API Keys & Webhooks — Manage your API keys and explore the docs.
          </p>
        </div>
        <div className="flex gap-2">
          <Button
            variant="secondary"
            icon={<ExternalLink className="w-4 h-4" />}
            onClick={() => window.open('/webhooks', '_self')}
          >
            Manage Webhooks
          </Button>
          <Button
            variant="default"
            icon={<Plus className="w-4 h-4" />}
            onClick={() => setShowCreateModal(true)}
          >
            Create API Key
          </Button>
        </div>
      </div>

      <Card variant="default">
        <CardContent className="pt-6">
          <h3 className="text-lg font-bold text-foreground mb-4 flex items-center gap-2">
            <Key className="w-5 h-5" />
            API Keys
          </h3>
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
            </div>
          ) : keys.length === 0 ? (
            <EmptyState
              icon={<Key className="w-12 h-12 text-muted-foreground" />}
              title="No API keys yet"
              description="Create an API key to authenticate your apps and scripts. Use the X-API-Key header or Authorization: Bearer &lt;key&gt;."
              variant="card"
            />
          ) : (
            <div className="space-y-3">
              {keys.map((k) => (
                <div
                  key={k.id}
                  className="flex items-center justify-between p-4 rounded-lg shadow-[0_0_8px_rgba(26,26,30,0.05)] bg-background/30 hover:bg-foreground/5 transition-colors"
                >
                  <div>
                    <div className="font-medium text-foreground">{k.name}</div>
                    <div className="text-sm font-mono text-muted-foreground">
                      {k.prefix}
                    </div>
                    <div className="text-xs text-muted-foreground mt-1">
                      Created {k.created}
                      {k.lastUsed !== 'Never' && ` · Last used ${k.lastUsed}`}
                    </div>
                    {k.scopes.length > 0 && (
                      <div className="flex gap-1 mt-2 flex-wrap">
                        {k.scopes.map((s) => (
                          <span
                            key={s}
                            className="text-xs px-2 py-0.5 rounded bg-muted text-muted-foreground"
                          >
                            {s}
                          </span>
                        ))}
                      </div>
                    )}
                  </div>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="text-destructive hover:bg-destructive/10"
                    onClick={() => setRevokeId(k.id)}
                    icon={<Trash2 className="w-4 h-4" />}
                  />
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      <Card variant="default" className="p-0 overflow-hidden bg-background/80">
        <SwaggerUIDoc useIframe={false} />
      </Card>

      {showCreateModal && (
        <CreateAPIKeyModal
          onClose={() => setShowCreateModal(false)}
          onCreate={handleCreate}
        />
      )}

      <ConfirmationDialog
        open={!!revokeId}
        onClose={() => setRevokeId(null)}
        onConfirm={() => revokeId && handleRevoke(revokeId)}
        title="Revoke API key"
        description="This will immediately invalidate the key. Any apps using it will stop working."
        confirmLabel="Revoke"
        variant="destructive"
      />
    </div>
  );
};
