"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { Loader2, X } from "lucide-react";

import { apiFetch } from "@/lib/client/api";
import { cn } from "@/lib/utils";

/**
 * "Stop showing this" for a Continue Watching card.
 *
 * A Continue Watching row can only leave the rail one of two ways now that no
 * position is recorded: the visitor marks it finished, or they say they are not
 * watching it any more. This is the second, and it is the one that has to exist
 * — the first is optional, and without either a title would sit in the rail
 * forever with no way out.
 *
 * It deletes the whole title rather than one episode's record, because the
 * intent behind the click is about the title, and because the store already keeps
 * the rail and the history log paired: a partial delete would leave the two
 * disagreeing.
 *
 * It is a separate component rather than inline JSX because the same control is
 * needed in two places — the home rail and `/history` — and the two live in
 * different component trees (one behind a client boundary, one on a Server
 * Component), so sharing it is the only way they can behave identically.
 */
export function ContinueDismissButton({
  tmdbId,
  mediaType,
  title,
  className,
}: {
  tmdbId: number;
  mediaType: "movie" | "tv";
  /** Used for the accessible name; the card already shows it visually. */
  title: string;
  className?: string;
}) {
  const router = useRouter();
  const [busy, setBusy] = useState(false);

  const dismiss = () => {
    if (busy) return;
    setBusy(true);

    void apiFetch(`/api/progress?tmdbId=${tmdbId}&mediaType=${mediaType}`, {
      method: "DELETE",
    })
      .then(() => router.refresh())
      // Leaving the card up is recoverable; a control stuck in a spinner is not.
      .catch(() => setBusy(false));
  };

  return (
    <button
      type="button"
      onClick={dismiss}
      disabled={busy}
      aria-label={`Stop showing ${title} in Continue Watching`}
      className={cn(
        "grid size-6 shrink-0 place-items-center rounded-full bg-black/65 text-white/80 backdrop-blur-sm",
        "transition hover:bg-black/85 hover:text-white disabled:opacity-50",
        className,
      )}
    >
      {busy ? <Loader2 className="size-3 animate-spin" /> : <X className="size-3" strokeWidth={2.4} />}
    </button>
  );
}
