"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { Trash2 } from "lucide-react";
import { toast } from "sonner";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

export function ClearChatHistoryButton({
  recipeId,
  disabled,
  onCleared,
}: {
  recipeId?: string;
  disabled?: boolean;
  onCleared: () => void;
}) {
  const t = useTranslations("chatHistory");
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [clearing, setClearing] = useState(false);

  async function handleClear() {
    setClearing(true);
    try {
      const params = new URLSearchParams();
      if (recipeId) params.set("recipeId", recipeId);
      else params.set("scope", "general");
      const res = await fetch(`/api/v1/ai/chat-history?${params.toString()}`, { method: "DELETE" });
      if (!res.ok) {
        toast.error(t("clearFailed"));
        return;
      }
      onCleared();
      toast.success(t("cleared"));
    } catch {
      toast.error(t("clearFailed"));
    } finally {
      setClearing(false);
      setConfirmOpen(false);
    }
  }

  return (
    <>
      <button
        type="button"
        onClick={() => setConfirmOpen(true)}
        disabled={disabled || clearing}
        className="p-1.5 rounded-md hover:bg-muted transition-colors text-muted-foreground disabled:opacity-40"
        aria-label={t("clearAriaLabel")}
      >
        <Trash2 className="h-4 w-4" />
      </button>

      <AlertDialog open={confirmOpen} onOpenChange={setConfirmOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t("clearConfirmTitle")}</AlertDialogTitle>
            <AlertDialogDescription>{t("clearConfirmDescription")}</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t("clearCancel")}</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => { void handleClear(); }}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {t("clearConfirm")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}
