import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import type { AdapterConfigFieldsProps } from "../types";
import {
  Field,
  DraftInput,
} from "../../components/agent-config-primitives";
import { ChoosePathButton } from "../../components/PathInstructionsModal";
import { useCompany } from "../../context/CompanyContext";
import { ollamaApi } from "../../api/ollama";

const inputClass =
  "w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40";
const instructionsFileHint =
  "Absolute path to a markdown file (e.g. AGENTS.md) that defines this agent's behavior. Injected into the system prompt at runtime.";

export function HermesLocalConfigFields({
  isCreate,
  values,
  set,
  config,
  eff,
  mark,
  hideInstructionsFile,
}: AdapterConfigFieldsProps) {
  const { selectedCompanyId } = useCompany();
  const companyId = selectedCompanyId;

  const [manualEntry, setManualEntry] = useState(false);

  const { data: ollamaStatus } = useQuery({
    queryKey: ["ollama", "status", companyId],
    queryFn: () => ollamaApi.status(companyId!),
    enabled: Boolean(companyId),
    staleTime: 60_000,
  });

  const { data: ollamaModels } = useQuery({
    queryKey: ["ollama", "models", companyId],
    queryFn: () => ollamaApi.models(companyId!),
    enabled: Boolean(companyId && ollamaStatus?.installed),
    staleTime: 60_000,
  });

  const currentModel = isCreate
    ? (values!.model ?? "")
    : eff("adapterConfig", "model", String(config.model ?? ""));

  function handleSelectModel(selectedModel: string) {
    if (selectedModel === "__manual__") {
      setManualEntry(true);
      return;
    }
    if (selectedModel === "") return;
    // Set fields when selecting an Ollama model
    if (isCreate) {
      // In create mode, CreateConfigValues does not have provider/base_url;
      // only model is stored via form values. The server resolves provider
      // at runtime from the model name or ~/.hermes/config.yaml.
      set!({ model: selectedModel });
    } else {
      // In edit mode, set all three fields atomically on adapterConfig
      mark("adapterConfig", "model", selectedModel);
      mark("adapterConfig", "provider", "custom");
      mark("adapterConfig", "base_url", "http://localhost:11434/v1");
    }
  }

  function formatModelLabel(m: { name: string; parameterSize: string; quantization: string; recommended: boolean; recommendationReason: string | null }) {
    const params = m.parameterSize ? ` (${m.parameterSize}, ${m.quantization})` : "";
    const recSuffix = m.recommended ? " - Recommended for your system" : "";
    const star = m.recommended ? "* " : "";
    return `${star}${m.name}${params}${recSuffix}`;
  }

  const showDropdown =
    ollamaStatus?.installed === true &&
    (ollamaModels?.models?.length ?? 0) > 0 &&
    !manualEntry;

  const showInstallCallout = ollamaStatus?.installed === false;

  return (
    <>
      {!hideInstructionsFile && (
        <Field label="Agent instructions file" hint={instructionsFileHint}>
          <div className="flex items-center gap-2">
            <DraftInput
              value={
                isCreate
                  ? values!.instructionsFilePath ?? ""
                  : eff(
                      "adapterConfig",
                      "instructionsFilePath",
                      String(config.instructionsFilePath ?? ""),
                    )
              }
              onCommit={(v) =>
                isCreate
                  ? set!({ instructionsFilePath: v })
                  : mark("adapterConfig", "instructionsFilePath", v || undefined)
              }
              immediate
              className={inputClass}
              placeholder="/absolute/path/to/AGENTS.md"
            />
            <ChoosePathButton />
          </div>
        </Field>
      )}

      <Field
        label="Model"
        hint={
          showDropdown
            ? "Select a locally pulled Ollama model. Recommended models are marked with *."
            : "Provider/model format (e.g. anthropic/claude-sonnet-4). Leave blank to use Hermes default."
        }
      >
        {showInstallCallout && (
          <div className="mb-2 rounded-md border border-amber-500/30 bg-amber-500/5 p-3 text-sm">
            <span className="text-amber-200">Ollama is not detected. </span>
            <a
              href={ollamaStatus.installUrl ?? "https://ollama.com/download"}
              target="_blank"
              rel="noopener noreferrer"
              className="text-amber-400 underline hover:text-amber-300"
            >
              Install Ollama
            </a>
            <span className="text-muted-foreground"> to use local models.</span>
          </div>
        )}

        {showDropdown ? (
          <select
            className={inputClass}
            value={currentModel || ""}
            onChange={(e) => handleSelectModel(e.target.value)}
          >
            <option value="">Select a model...</option>
            {(ollamaModels?.models ?? []).map((m) => (
              <option key={m.name} value={m.name}>
                {formatModelLabel(m)}
              </option>
            ))}
            <option value="__manual__">Other (manual entry)...</option>
          </select>
        ) : (
          <DraftInput
            value={currentModel}
            onCommit={(v) =>
              isCreate
                ? set!({ model: v })
                : mark("adapterConfig", "model", v || undefined)
            }
            immediate
            className={inputClass}
            placeholder="anthropic/claude-sonnet-4"
          />
        )}
      </Field>

      {!isCreate && (
        <>
          <Field
            label="Toolsets"
            hint="Comma-separated toolset names (e.g. terminal,file,web). Leave blank for defaults."
          >
            <DraftInput
              value={eff("adapterConfig", "toolsets", String(config.toolsets ?? ""))}
              onCommit={(v) =>
                mark("adapterConfig", "toolsets", v || undefined)
              }
              immediate
              className={inputClass}
              placeholder="terminal,file,web"
            />
          </Field>
          <Field
            label="Persist session"
            hint="Keep conversation history between heartbeat runs."
          >
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                className="h-4 w-4 rounded border-border accent-primary"
                checked={eff("adapterConfig", "persistSession", config.persistSession !== false)}
                onChange={(e) =>
                  mark("adapterConfig", "persistSession", e.target.checked)
                }
              />
              <span className="text-sm text-muted-foreground">Enabled</span>
            </label>
          </Field>
          <Field
            label="Timeout (seconds)"
            hint="Maximum execution time per heartbeat run."
          >
            <DraftInput
              value={String(
                eff("adapterConfig", "timeoutSec", Number(config.timeoutSec ?? 300)),
              )}
              onCommit={(v) =>
                mark("adapterConfig", "timeoutSec", Number(v) || 300)
              }
              immediate
              className={inputClass}
              placeholder="300"
            />
          </Field>
        </>
      )}
    </>
  );
}
