// src/components/content/content-keywords-panel.tsx
"use client";
// Mots-clés liés à une page : principal (badge), définir principal, retirer, ajouter.
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  addContentKeywordsAction,
  type ContentKeywordLink,
  getContentKeywordsAction,
  removeContentKeywordAction,
  setContentPrimaryKeywordAction,
} from "@/lib/content/actions";
import { fetchKeywordsForSiteAction } from "@/lib/keywords/actions";

export function ContentKeywordsPanel({
  contentItemId,
  siteId,
}: {
  contentItemId: string;
  siteId: string;
}) {
  const [links, setLinks] = useState<ContentKeywordLink[]>([]);
  const [query, setQuery] = useState("");
  const [candidates, setCandidates] = useState<{ id: string; term: string }[]>(
    [],
  );

  const reload = useCallback(async () => {
    setLinks(await getContentKeywordsAction(contentItemId));
  }, [contentItemId]);

  useEffect(() => {
    void reload();
  }, [reload]);

  useEffect(() => {
    if (query.trim().length < 2) {
      setCandidates([]);
      return;
    }
    let on = true;
    void fetchKeywordsForSiteAction(siteId).then((all) => {
      if (!on) return;
      const linked = new Set(links.map((l) => l.keywordId));
      setCandidates(
        all
          .filter(
            (k) =>
              !linked.has(k.id) &&
              k.term.toLowerCase().includes(query.toLowerCase()),
          )
          .slice(0, 8)
          .map((k) => ({ id: k.id, term: k.term })),
      );
    });
    return () => {
      on = false;
    };
  }, [query, siteId, links]);

  async function setPrimary(id: string) {
    await setContentPrimaryKeywordAction(contentItemId, id);
    await reload();
  }
  async function remove(id: string) {
    const res = await removeContentKeywordAction(contentItemId, id);
    if (!res.ok) toast.error(res.error ?? "Impossible");
    await reload();
  }
  async function add(id: string) {
    await addContentKeywordsAction(contentItemId, [id]);
    setQuery("");
    await reload();
  }

  return (
    <div className="rounded-lg border p-3">
      <div className="mb-2 font-medium text-sm">Mots-clés</div>
      <ul className="grid gap-1">
        {links.map((l) => (
          <li key={l.keywordId} className="flex items-center gap-2 text-sm">
            <span className="flex-1 truncate">{l.term}</span>
            {l.role === "primary" ? (
              <Badge variant="secondary">Principal</Badge>
            ) : (
              <>
                <Button
                  size="sm"
                  variant="ghost"
                  onClick={() => setPrimary(l.keywordId)}
                >
                  Définir principal
                </Button>
                <Button
                  size="sm"
                  variant="ghost"
                  className="text-destructive"
                  onClick={() => remove(l.keywordId)}
                >
                  Retirer
                </Button>
              </>
            )}
          </li>
        ))}
        {links.length === 0 ? (
          <li className="text-muted-foreground text-sm">Aucun mot-clé lié.</li>
        ) : null}
      </ul>
      <div className="mt-2 grid gap-1">
        <Input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Ajouter un mot-clé…"
          aria-label="Ajouter un mot-clé"
        />
        {candidates.map((c) => (
          <Button
            key={c.id}
            size="sm"
            variant="ghost"
            className="justify-start"
            onClick={() => add(c.id)}
          >
            + {c.term}
          </Button>
        ))}
      </div>
    </div>
  );
}
