import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  useFireworksModels,
  useOllamaModels,
  useOpenRouterModels,
} from "@/hooks/use-ai";
import { RefreshCw, Loader2 } from "lucide-react";
import type { AiProvider, OllamaModel } from "@/types";

interface Props {
  provider: AiProvider;
  ollamaUrl: string;
  onOllamaUrlChange: (url: string) => void;
  fireworksApiKey: string;
  onFireworksApiKeyChange: (key: string) => void;
  openrouterApiKey: string;
  onOpenRouterApiKeyChange: (key: string) => void;
  model: string;
  onModelChange: (model: string) => void;
}

export function AiSettingsFields({
  provider,
  ollamaUrl,
  onOllamaUrlChange,
  fireworksApiKey,
  onFireworksApiKeyChange,
  openrouterApiKey,
  onOpenRouterApiKeyChange,
  model,
  onModelChange,
}: Props) {
  if (provider === "fireworks") {
    return (
      <FireworksFields
        apiKey={fireworksApiKey}
        onApiKeyChange={onFireworksApiKeyChange}
        model={model}
        onModelChange={onModelChange}
      />
    );
  }

  if (provider === "openrouter") {
    return (
      <OpenRouterFields
        apiKey={openrouterApiKey}
        onApiKeyChange={onOpenRouterApiKeyChange}
        model={model}
        onModelChange={onModelChange}
      />
    );
  }

  return (
    <OllamaFields
      ollamaUrl={ollamaUrl}
      onOllamaUrlChange={onOllamaUrlChange}
      model={model}
      onModelChange={onModelChange}
    />
  );
}

function OllamaFields({
  ollamaUrl,
  onOllamaUrlChange,
  model,
  onModelChange,
}: {
  ollamaUrl: string;
  onOllamaUrlChange: (url: string) => void;
  model: string;
  onModelChange: (model: string) => void;
}) {
  const {
    data: models,
    isLoading,
    isError,
    refetch,
  } = useOllamaModels(ollamaUrl);

  return (
    <>
      <div className="flex flex-col gap-1.5">
        <label className="text-xs text-muted-foreground">Ollama URL</label>
        <Input
          value={ollamaUrl}
          onChange={(e) => onOllamaUrlChange(e.target.value)}
          placeholder="http://localhost:11434"
          className="h-8 text-xs"
        />
      </div>

      <ModelDropdown
        models={models}
        loading={isLoading}
        errored={isError}
        errorText="Cannot connect to Ollama"
        onRefresh={() => refetch()}
        model={model}
        onModelChange={onModelChange}
      />
    </>
  );
}

function FireworksFields({
  apiKey,
  onApiKeyChange,
  model,
  onModelChange,
}: {
  apiKey: string;
  onApiKeyChange: (key: string) => void;
  model: string;
  onModelChange: (model: string) => void;
}) {
  const {
    data: models,
    isLoading,
    isError,
    refetch,
  } = useFireworksModels(apiKey);

  return (
    <>
      <div className="flex flex-col gap-1.5">
        <label className="text-xs text-muted-foreground">Fireworks API key</label>
        <Input
          type="password"
          value={apiKey}
          onChange={(e) => onApiKeyChange(e.target.value)}
          placeholder="fw_..."
          className="h-8 text-xs"
          autoComplete="off"
        />
        <p className="text-[10px] text-muted-foreground/70">
          Stored locally; sent only to api.fireworks.ai.
        </p>
      </div>

      <ModelDropdown
        models={models}
        loading={isLoading}
        errored={isError}
        errorText="Cannot reach Fireworks (check API key)"
        onRefresh={() => refetch()}
        model={model}
        onModelChange={onModelChange}
        emptyHint={apiKey.trim() ? "Click ↻ to load models" : "Enter API key first"}
      />
    </>
  );
}

function OpenRouterFields({
  apiKey,
  onApiKeyChange,
  model,
  onModelChange,
}: {
  apiKey: string;
  onApiKeyChange: (key: string) => void;
  model: string;
  onModelChange: (model: string) => void;
}) {
  const {
    data: models,
    isLoading,
    isError,
    refetch,
  } = useOpenRouterModels(apiKey);

  return (
    <>
      <div className="flex flex-col gap-1.5">
        <label className="text-xs text-muted-foreground">OpenRouter API key</label>
        <Input
          type="password"
          value={apiKey}
          onChange={(e) => onApiKeyChange(e.target.value)}
          placeholder="sk-or-..."
          className="h-8 text-xs"
          autoComplete="off"
        />
        <p className="text-[10px] text-muted-foreground/70">
          Stored locally; sent only to openrouter.ai.
        </p>
      </div>

      <ModelDropdown
        models={models}
        loading={isLoading}
        errored={isError}
        errorText="Cannot reach OpenRouter (check API key)"
        onRefresh={() => refetch()}
        model={model}
        onModelChange={onModelChange}
        emptyHint={apiKey.trim() ? "Click ↻ to load models" : "Enter API key first"}
      />
    </>
  );
}

function ModelDropdown({
  models,
  loading,
  errored,
  errorText,
  onRefresh,
  model,
  onModelChange,
  emptyHint,
}: {
  models: OllamaModel[] | undefined;
  loading: boolean;
  errored: boolean;
  errorText: string;
  onRefresh: () => void;
  model: string;
  onModelChange: (model: string) => void;
  emptyHint?: string;
}) {
  return (
    <div className="flex flex-col gap-1.5">
      <div className="flex items-center justify-between">
        <label className="text-xs text-muted-foreground">Model</label>
        <Button
          size="sm"
          variant="ghost"
          className="h-5 w-5 p-0"
          onClick={onRefresh}
          disabled={loading}
          title="Refresh models"
        >
          {loading ? (
            <Loader2 className="h-3 w-3 animate-spin" />
          ) : (
            <RefreshCw className="h-3 w-3" />
          )}
        </Button>
      </div>
      {errored ? (
        <p className="text-xs text-destructive">{errorText}</p>
      ) : (
        <Select value={model} onValueChange={onModelChange}>
          <SelectTrigger className="h-8 w-full text-xs">
            <SelectValue placeholder={emptyHint ?? "Select a model"} />
          </SelectTrigger>
          <SelectContent>
            {models?.map((m) => (
              <SelectItem key={m.name} value={m.name}>
                {m.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      )}
    </div>
  );
}
