import { useMemo, useState } from 'react';
import { ExternalLink, Search } from 'lucide-react';
import { api } from '@/api/client';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import {
  ACP_PROVIDER_CATALOG,
  buildAcpProviderConfigPatch,
  type AcpCatalogEntry,
} from '@/data/acp-provider-catalog';

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  /** Fired after a successful add so the parent can refetch the snapshot. */
  onAdded: (id: string) => void;
}

/**
 * v2.3 Phase 5 (design.md §7.3). Search the curated ACP catalog and register a
 * provider: PATCH /api/providers/config with its custom-ACP override, then
 * refresh that one provider. Adding only edits config — it does NOT install the
 * binary, so the provider shows "Not installed" until the CLI is on PATH.
 */
export function AddProviderModal({ open, onOpenChange, onAdded }: Props) {
  const [query, setQuery] = useState('');
  const [busyId, setBusyId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return ACP_PROVIDER_CATALOG;
    return ACP_PROVIDER_CATALOG.filter(
      (e) =>
        e.id.toLowerCase().includes(q) ||
        e.label.toLowerCase().includes(q) ||
        e.description.toLowerCase().includes(q),
    );
  }, [query]);

  async function add(entry: AcpCatalogEntry): Promise<void> {
    setBusyId(entry.id);
    setError(null);
    try {
      await api.coder.patchProvidersConfig(buildAcpProviderConfigPatch(entry));
      await api.coder.refreshProviders([entry.id]);
      onAdded(entry.id);
      onOpenChange(false);
    } catch (err) {
      // 422 from PATCH (invalid override) surfaces here as ApiError.message.
      setError(err instanceof Error ? err.message : 'failed to add provider');
    } finally {
      setBusyId(null);
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg max-h-[85vh] grid-rows-[auto_minmax(0,1fr)_auto]">
        <DialogHeader>
          <DialogTitle>Add ACP provider</DialogTitle>
          <DialogDescription>
            Registers the provider in your coder config. It is not installed — install the CLI
            yourself; until it's on PATH it shows as “Not installed”.
          </DialogDescription>
        </DialogHeader>

        <div className="flex flex-col min-h-0 gap-3">
          <div className="relative shrink-0">
            <Search className="absolute left-2 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground" />
            <Input
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Search providers…"
              className="pl-7"
            />
          </div>

          <div className="flex-1 min-h-0 rounded-md border overflow-y-auto overscroll-contain divide-y">
            {filtered.length === 0 && (
              <div className="px-3 py-2 text-sm text-muted-foreground">No matching providers.</div>
            )}
            {filtered.map((e) => (
              <div key={e.id} className="px-3 py-2.5 space-y-1.5">
                <div className="flex items-start justify-between gap-2">
                  <div className="min-w-0">
                    <div className="text-sm font-medium">{e.label}</div>
                    <div className="text-xs text-muted-foreground">{e.description}</div>
                  </div>
                  <Button
                    size="sm"
                    disabled={busyId !== null}
                    onClick={() => void add(e)}
                  >
                    {busyId === e.id ? 'Adding…' : 'Add'}
                  </Button>
                </div>
                <div className="font-mono text-[11px] text-muted-foreground truncate">
                  $ {e.command.join(' ')}
                </div>
                <div className="flex items-center gap-3">
                  <a
                    href={e.installUrl}
                    target="_blank"
                    rel="noreferrer"
                    className="inline-flex items-center gap-1 text-xs text-primary hover:underline"
                  >
                    Install {e.label} <ExternalLink className="size-3" />
                  </a>
                  {e.installCmd && (
                    <span className="font-mono text-[11px] text-muted-foreground truncate">
                      {e.installCmd}
                    </span>
                  )}
                </div>
              </div>
            ))}
          </div>

          {error && <div className="text-sm text-destructive shrink-0">{error}</div>}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={busyId !== null}>
            Close
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
