"use client";

import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import {
  resetAssistantName,
  resetAssistantSystemPrompt,
  setAssistantEnabled,
  setAssistantName,
  setAssistantSystemPrompt,
} from "@/app/settings/assistant-actions";
import { DEFAULT_ASSISTANT_NAME, MAX_ASSISTANT_NAME_LENGTH } from "@/lib/assistant-config";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";

type Props = {
  enabled: boolean;
  name: string;
  systemPrompt: string | null;
  defaultSystemPrompt: string;
};

export function AssistantSettings({ enabled, name, systemPrompt, defaultSystemPrompt }: Props) {
  const [isPending, startTransition] = useTransition();
  const router = useRouter();

  const effectivePrompt = systemPrompt ?? defaultSystemPrompt;
  const [savedName, setSavedName] = useState(name);
  const [draftName, setDraftName] = useState(name);
  const [savedPrompt, setSavedPrompt] = useState(systemPrompt);
  const [draftPrompt, setDraftPrompt] = useState(effectivePrompt);

  const nameDirty = draftName.trim() !== savedName;
  const promptDirty =
    savedPrompt === null
      ? draftPrompt.trim() !== defaultSystemPrompt.trim()
      : draftPrompt.trim() !== savedPrompt.trim();
  const usingDefaultPrompt = savedPrompt === null;

  function toggle(next: boolean) {
    startTransition(async () => {
      await setAssistantEnabled(next);
      router.refresh();
    });
  }

  function saveName() {
    const next = draftName.trim();
    if (!next) return;

    startTransition(async () => {
      await setAssistantName(next);
      setSavedName(next);
      setDraftName(next);
      router.refresh();
    });
  }

  function savePrompt() {
    const next = draftPrompt.trim();
    if (!next) return;

    startTransition(async () => {
      const isDefault = next === defaultSystemPrompt.trim();
      await setAssistantSystemPrompt(isDefault ? null : next);
      setSavedPrompt(isDefault ? null : next);
      setDraftPrompt(next);
      router.refresh();
    });
  }

  function handleResetName() {
    startTransition(async () => {
      await resetAssistantName();
      setSavedName(DEFAULT_ASSISTANT_NAME);
      setDraftName(DEFAULT_ASSISTANT_NAME);
      router.refresh();
    });
  }

  function handleResetPrompt() {
    startTransition(async () => {
      await resetAssistantSystemPrompt();
      setSavedPrompt(null);
      setDraftPrompt(defaultSystemPrompt);
      router.refresh();
    });
  }

  return (
    <div className="flex flex-col gap-5">
      <label className="flex items-center justify-between gap-4">
        <div className="min-w-0">
          <div className="text-sm font-medium">AI assistant</div>
          <p className="muted text-[12px] mt-0.5">
            Off by default. Turn on to show a chat bubble in the bottom-right corner.
          </p>
        </div>
        <Switch
          checked={enabled}
          disabled={isPending}
          onCheckedChange={toggle}
          aria-label="AI assistant"
        />
      </label>

      <div className="flex flex-col gap-2">
        <div className="flex items-end justify-between gap-3">
          <div className="min-w-0 flex-1">
            <label htmlFor="assistant-name" className="text-sm font-medium">
              Assistant name
            </label>
            <p className="muted text-[12px] mt-0.5">Shown in the chat bubble and message labels.</p>
          </div>
          <Button
            type="button"
            variant="ghost"
            size="sm"
            disabled={isPending || savedName === DEFAULT_ASSISTANT_NAME}
            onClick={handleResetName}
          >
            Reset
          </Button>
        </div>
        <Input
          id="assistant-name"
          value={draftName}
          maxLength={MAX_ASSISTANT_NAME_LENGTH}
          disabled={isPending}
          onChange={(event) => setDraftName(event.target.value)}
          aria-label="Assistant name"
        />
        <Button
          type="button"
          size="sm"
          disabled={!nameDirty || isPending || !draftName.trim()}
          onClick={saveName}
        >
          {isPending ? "Saving…" : "Save name"}
        </Button>
      </div>

      <div className="flex flex-col gap-2">
        <div className="flex items-end justify-between gap-3">
          <div className="min-w-0 flex-1">
            <label htmlFor="assistant-system-prompt" className="text-sm font-medium">
              System prompt
            </label>
            <p className="muted text-[12px] mt-0.5">
              Instructions sent to the model before each conversation. Customize tone, priorities,
              or household context.
            </p>
          </div>
          <Button
            type="button"
            variant="ghost"
            size="sm"
            disabled={isPending || usingDefaultPrompt}
            onClick={handleResetPrompt}
          >
            Reset
          </Button>
        </div>
        <textarea
          id="assistant-system-prompt"
          value={draftPrompt}
          rows={10}
          disabled={isPending}
          onChange={(event) => setDraftPrompt(event.target.value)}
          aria-label="Assistant system prompt"
          className="input min-h-[180px] resize-y font-mono text-[12px] leading-relaxed"
        />
        <Button
          type="button"
          size="sm"
          disabled={!promptDirty || isPending || !draftPrompt.trim()}
          onClick={savePrompt}
        >
          {isPending ? "Saving…" : "Save prompt"}
        </Button>
      </div>
    </div>
  );
}
