import * as api from "@client/api";
import { parseSearchTermsInput } from "@client/pages/orchestrator/automatic-run";
import { KeywordSetPicker } from "@client/pages/orchestrator/KeywordSetPicker";
import { TokenizedInput } from "@client/pages/orchestrator/TokenizedInput";
import type { KeywordSet } from "@shared/types";
import type React from "react";
import { useCallback, useState } from "react";
import { toast } from "sonner";
import {
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { Button } from "@/components/ui/button";

type KeywordSetsSettingsSectionProps = {
  isLoading: boolean;
  isSaving: boolean;
};

export const KeywordSetsSettingsSection: React.FC<
  KeywordSetsSettingsSectionProps
> = ({ isLoading, isSaving }) => {
  const [activeSet, setActiveSet] = useState<KeywordSet | null>(null);
  const [terms, setTerms] = useState<string[]>([]);
  const [termDraft, setTermDraft] = useState("");
  const [isPersisting, setIsPersisting] = useState(false);

  const handleActiveSetChange = useCallback((set: KeywordSet) => {
    setActiveSet(set);
    setTerms(set.terms.map((t) => t.trim()).filter(Boolean));
    setTermDraft("");
  }, []);

  const handleSave = async () => {
    if (!activeSet) {
      toast.error("Select a keyword set first");
      return;
    }
    const normalized = terms.map((t) => t.trim()).filter(Boolean);
    if (normalized.length === 0) {
      toast.error("Add at least one search term");
      return;
    }
    setIsPersisting(true);
    try {
      const updated = await api.updateKeywordSet(activeSet.id, {
        terms: normalized,
      });
      setActiveSet(updated);
      setTerms(updated.terms);
      toast.success(`Saved "${updated.name}" keyword set`);
    } catch (error) {
      const message =
        error instanceof Error ? error.message : "Failed to save keyword set";
      toast.error(message);
    } finally {
      setIsPersisting(false);
    }
  };

  const busy = isLoading || isSaving || isPersisting;

  return (
    <AccordionItem value="keyword-sets" className="border rounded-lg px-4">
      <AccordionTrigger className="hover:no-underline py-4">
        <span className="text-base font-semibold">Search keyword sets</span>
      </AccordionTrigger>
      <AccordionContent className="pb-4 space-y-4">
        <p className="text-sm text-muted-foreground">
          Named term lists used when you run the automatic pipeline (e.g. SDET
          vs Caseware vs lead roles). The active set is used for discovery.
        </p>
        <KeywordSetPicker
          disabled={busy}
          onActiveSetChange={handleActiveSetChange}
        />
        <TokenizedInput
          id="settings-keyword-set-terms"
          values={terms}
          draft={termDraft}
          parseInput={parseSearchTermsInput}
          onDraftChange={setTermDraft}
          onValuesChange={setTerms}
          placeholder="Type a term and press Enter"
          helperText="Terms for the active set above. Save when you are done editing."
          removeLabelPrefix="Remove"
          disabled={busy || !activeSet}
        />
        <div className="flex justify-end">
          <Button
            type="button"
            onClick={() => void handleSave()}
            disabled={busy || !activeSet}
          >
            {isPersisting ? "Saving…" : "Save keyword set"}
          </Button>
        </div>
      </AccordionContent>
    </AccordionItem>
  );
};
