"use client";

import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";

type BulkAction = "add" | "remove";

function selectedMediaIds() {
  return Array.from(document.querySelectorAll<HTMLInputElement>('input[data-inventory-select="true"]:checked'))
    .map((input) => input.value)
    .filter(Boolean);
}

export function InventoryBulkActions() {
  const router = useRouter();
  const [message, setMessage] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();

  function run(action: BulkAction) {
    const mediaItemIds = selectedMediaIds();
    if (!mediaItemIds.length) {
      setMessage("Select at least one title first.");
      return;
    }

    setMessage(null);
    startTransition(async () => {
      const response = await fetch("/api/admin/inventory/classics", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ action, mediaItemIds }),
      });

      if (!response.ok) {
        setMessage("Bulk update failed.");
        return;
      }

      setMessage(action === "add" ? "Marked selected titles as Timeless." : "Removed Timeless from selected titles.");
      router.refresh();
    });
  }

  return (
    <div className="admin-panel flex flex-wrap items-center gap-2 p-4">
      <p className="mr-2 text-sm text-admin-muted">Bulk</p>
      <button disabled={isPending} onClick={() => run("add")} className="admin-nav-button px-3 py-2 text-sm font-medium disabled:opacity-60" type="button">
        Mark Timeless
      </button>
      <button disabled={isPending} onClick={() => run("remove")} className="admin-nav-button px-3 py-2 text-sm font-medium disabled:opacity-60" type="button">
        Remove Timeless
      </button>
      {message ? <p className="basis-full text-xs text-admin-muted">{message}</p> : null}
    </div>
  );
}
