"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { Key, Trash2, Check } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";

type Provider = "openai" | "anthropic" | "openrouter" | "ollama";

const PROVIDERS: { id: Provider; label: string; placeholder: string }[] = [
  { id: "openai", label: "OpenAI", placeholder: "sk-..." },
  { id: "anthropic", label: "Anthropic", placeholder: "sk-ant-..." },
  { id: "openrouter", label: "OpenRouter", placeholder: "sk-or-..." },
  { id: "ollama", label: "Ollama (local)", placeholder: "Base URL uses env var" },
];

export function ByokManager({ initialKeys }: { initialKeys: string[] }) {
  const t = useTranslations("settingsForm");
  const [configuredKeys, setConfiguredKeys] = useState<Set<string>>(new Set(initialKeys));
  const [inputs, setInputs] = useState<Partial<Record<Provider, string>>>({});
  const [saving, setSaving] = useState<Provider | null>(null);
  const [removing, setRemoving] = useState<Provider | null>(null);

  async function saveKey(provider: Provider) {
    const apiKey = inputs[provider]?.trim();
    if (!apiKey) return;
    setSaving(provider);
    try {
      const res = await fetch("/api/v1/ai-keys", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ provider, apiKey }),
      });
      if (res.ok) {
        setConfiguredKeys((prev) => new Set([...prev, provider]));
        setInputs((prev) => ({ ...prev, [provider]: "" }));
        toast.success(t("byokSaved", { provider }));
      } else {
        toast.error(t("byokSaveFailed"));
      }
    } finally {
      setSaving(null);
    }
  }

  async function removeKey(provider: Provider) {
    setRemoving(provider);
    try {
      const res = await fetch(`/api/v1/ai-keys/${provider}`, { method: "DELETE" });
      if (res.ok) {
        setConfiguredKeys((prev) => { const s = new Set(prev); s.delete(provider); return s; });
        toast.success(t("byokRemoved", { provider }));
      } else {
        toast.error(t("byokRemoveFailed"));
      }
    } finally {
      setRemoving(null);
    }
  }

  return (
    <div className="space-y-4">
      {PROVIDERS.map((p) => {
        const hasKey = configuredKeys.has(p.id);
        const isOllama = p.id === "ollama";
        return (
          <div key={p.id} className="flex items-center gap-3">
            <div className="w-28 shrink-0 flex items-center gap-2">
              <Key className="h-3.5 w-3.5 text-muted-foreground" />
              <span className="text-sm font-medium">{p.label}</span>
            </div>
            {hasKey ? (
              <div className="flex items-center gap-2 flex-1">
                <Badge variant="secondary" className="gap-1">
                  <Check className="h-3 w-3" />
                  {t("byokConfigured")}
                </Badge>
                <Button
                  variant="ghost"
                  size="sm"
                  className="text-destructive hover:text-destructive h-7"
                  disabled={removing === p.id}
                  onClick={() => { void removeKey(p.id); }}
                >
                  <Trash2 className="h-3.5 w-3.5" />
                </Button>
              </div>
            ) : isOllama ? (
              <span className="text-sm text-muted-foreground">{t("byokOllamaHint")}</span>
            ) : (
              <div className="flex items-center gap-2 flex-1">
                <Input
                  type="password"
                  placeholder={p.placeholder}
                  value={inputs[p.id] ?? ""}
                  onChange={(e) => setInputs((prev) => ({ ...prev, [p.id]: e.target.value }))}
                  className="h-8 text-sm"
                  onKeyDown={(e) => { if (e.key === "Enter") { void saveKey(p.id); } }}
                />
                <Button
                  size="sm"
                  className="h-8"
                  disabled={saving === p.id || !inputs[p.id]?.trim()}
                  onClick={() => { void saveKey(p.id); }}
                >
                  {saving === p.id ? t("byokSaving") : t("byokSave")}
                </Button>
              </div>
            )}
          </div>
        );
      })}
      <p className="text-xs text-muted-foreground">
        {t("byokFooter")}
      </p>
    </div>
  );
}
