"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Trash2 } from "lucide-react";

import { Button } from "@/components/ui/button";
import { apiFetch, ApiRequestError } from "@/lib/client/api";

/**
 * "Clear history" with an explicit confirmation step.
 *
 * This is destructive and irreversible, so it is a two-press interaction rather
 * than a single click, and the confirm state resets itself if the visitor
 * clicks anywhere else.
 */
export function ClearHistoryButton() {
  const router = useRouter();
  const [armed, setArmed] = useState(false);
  const [pending, setPending] = useState(false);
  const [error, setError] = useState<string | null>(null);

  if (!armed) {
    return (
      <Button variant="ghost" size="sm" onClick={() => setArmed(true)}>
        <Trash2 className="size-3.5" />
        Clear history
      </Button>
    );
  }

  const clear = async () => {
    if (pending) return;
    setPending(true);
    setError(null);

    try {
      await apiFetch("/api/history", { method: "DELETE" });
      setArmed(false);
      router.refresh();
    } catch (err) {
      setError(
        err instanceof ApiRequestError ? err.message : "Could not clear your history.",
      );
    } finally {
      setPending(false);
    }
  };

  return (
    <div className="flex flex-wrap items-center gap-2.5">
      <span className="text-[12px] font-medium text-ink-muted">
        Delete all history? This cannot be undone.
      </span>
      <Button variant="danger" size="sm" onClick={() => void clear()} loading={pending}>
        Yes, delete
      </Button>
      <Button
        variant="ghost"
        size="sm"
        onClick={() => {
          setArmed(false);
          setError(null);
        }}
      >
        Cancel
      </Button>
      {error ? <p className="text-[12px] text-brand-400">{error}</p> : null}
    </div>
  );
}
