import { useState } from "react";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { useAiSettings, useSaveAiSettings } from "@/hooks/use-ai";
import { Settings } from "lucide-react";
import { toast } from "sonner";
import { AiSettingsFields } from "./AiSettingsFields";
import type { AiProvider } from "@/types";

const SUPPORTED_PROVIDERS: { value: AiProvider; label: string }[] = [
  { value: "ollama", label: "Ollama (local)" },
  { value: "fireworks", label: "Fireworks AI" },
  { value: "openrouter", label: "OpenRouter" },
];

export function AiSettingsPopover() {
  const { data: settings } = useAiSettings();
  const saveMutation = useSaveAiSettings();

  const [provider, setProvider] = useState<AiProvider | null>(null);
  const [url, setUrl] = useState<string | null>(null);
  const [fireworksKey, setFireworksKey] = useState<string | null>(null);
  const [openrouterKey, setOpenrouterKey] = useState<string | null>(null);
  const [model, setModel] = useState<string | null>(null);

  const currentProvider: AiProvider =
    provider ?? settings?.provider ?? "ollama";
  const currentUrl = url ?? settings?.ollama_url ?? "http://localhost:11434";
  const currentFireworksKey =
    fireworksKey ?? settings?.fireworks_api_key ?? "";
  const currentOpenrouterKey =
    openrouterKey ?? settings?.openrouter_api_key ?? "";
  const currentModel = model ?? settings?.model ?? "";

  const handleProviderChange = (next: AiProvider) => {
    if (next === currentProvider) return;
    setProvider(next);
    // Model lists differ between providers — drop the previous selection.
    setModel("");
  };

  const handleSave = () => {
    saveMutation.mutate(
      {
        provider: currentProvider,
        ollama_url: currentUrl,
        fireworks_api_key:
          currentProvider === "fireworks"
            ? currentFireworksKey.trim() || undefined
            : settings?.fireworks_api_key,
        openrouter_api_key:
          currentProvider === "openrouter"
            ? currentOpenrouterKey.trim() || undefined
            : settings?.openrouter_api_key,
        model: currentModel,
      },
      {
        onSuccess: () => toast.success("AI settings saved"),
        onError: (err) =>
          toast.error("Failed to save AI settings", {
            description: String(err),
          }),
      }
    );
  };

  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button
          size="sm"
          variant="ghost"
          className="h-6 w-6 p-0"
          title="AI Settings"
        >
          <Settings className="h-3 w-3" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-80" align="end">
        <div className="flex flex-col gap-3">
          <h4 className="text-sm font-medium">AI Settings</h4>

          <div className="flex flex-col gap-1.5">
            <label className="text-xs text-muted-foreground">Provider</label>
            <Select
              value={currentProvider}
              onValueChange={(v) => handleProviderChange(v as AiProvider)}
            >
              <SelectTrigger className="h-8 w-full text-xs">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {SUPPORTED_PROVIDERS.map((p) => (
                  <SelectItem key={p.value} value={p.value}>
                    {p.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <AiSettingsFields
            provider={currentProvider}
            ollamaUrl={currentUrl}
            onOllamaUrlChange={setUrl}
            fireworksApiKey={currentFireworksKey}
            onFireworksApiKeyChange={setFireworksKey}
            openrouterApiKey={currentOpenrouterKey}
            onOpenRouterApiKeyChange={setOpenrouterKey}
            model={currentModel}
            onModelChange={setModel}
          />

          <Button size="sm" className="h-7 text-xs" onClick={handleSave}>
            Save
          </Button>
        </div>
      </PopoverContent>
    </Popover>
  );
}
