"use client";

import { useRef, useState } from "react";
import { useFormStatus } from "react-dom";
import ConfirmDialog from "@/components/ui/ConfirmDialog";
import { toggleProductStatus } from "./actions";

/**
 * `useFormStatus` only reports on the form it is rendered inside, so the trigger
 * and the dialog are split into their own components rather than reading a
 * `busy` flag from the parent's state. Pending now comes from React instead of
 * a hand-managed boolean that could survive an early return.
 */
function TriggerButton({ active, onOpen }: { active: boolean; onOpen: () => void }) {
  const { pending } = useFormStatus();

  return (
    <button
      type="button"
      onClick={onOpen}
      disabled={pending}
      className={`rounded-lg px-4 py-2 text-sm font-medium ${
        active
          ? "bg-gray-100 text-gray-700 hover:bg-gray-200"
          : "bg-[#CC1414] text-white hover:bg-[#a30f0f]"
      } disabled:opacity-60`}
    >
      {pending ? "…" : active ? "Deactivate" : "Activate"}
    </button>
  );
}

function ConfirmStep({
  active,
  open,
  onCancel,
  onConfirm,
}: {
  active: boolean;
  open: boolean;
  onCancel: () => void;
  onConfirm: () => void;
}) {
  const { pending } = useFormStatus();

  return (
    <ConfirmDialog
      open={open}
      title={`${active ? "Deactivate" : "Activate"} this product?`}
      description={`This product will be marked as ${active ? "inactive" : "active"}.`}
      confirmLabel={active ? "Deactivate" : "Activate"}
      loading={pending}
      onCancel={onCancel}
      onConfirm={onConfirm}
    />
  );
}

/**
 * The only interactive part of the product page. It stays on the client purely
 * because the confirmation step needs local open/closed state; the mutation
 * itself is a Server Action posted by the surrounding form, so no product data
 * or auth token has to travel to the browser for it to work.
 */
export default function StatusToggle({ id, active }: { id: number; active: boolean }) {
  const [confirmOpen, setConfirmOpen] = useState(false);
  const formRef = useRef<HTMLFormElement>(null);

  return (
    <form ref={formRef} action={toggleProductStatus}>
      <input type="hidden" name="id" value={id} />
      <input type="hidden" name="next" value={active ? "inactive" : "active"} />

      <TriggerButton active={active} onOpen={() => setConfirmOpen(true)} />

      <ConfirmStep
        active={active}
        open={confirmOpen}
        onCancel={() => setConfirmOpen(false)}
        onConfirm={() => {
          setConfirmOpen(false);
          // `requestSubmit` runs the form's action, which is what gives the
          // buttons below their pending state via `useFormStatus`.
          formRef.current?.requestSubmit();
        }}
      />
    </form>
  );
}
