"use client";

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

/**
 * Split out so `useFormStatus` has a form to read from — it only reports on the
 * form it renders inside, so the pending flag cannot be lifted into the parent.
 */
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 commodity product?`}
      description={`This commodity product will be marked as ${active ? "inactive" : "active"}.`}
      confirmLabel={active ? "Deactivate" : "Activate"}
      loading={pending}
      onCancel={onCancel}
      onConfirm={onConfirm}
    />
  );
}

/**
 * The page's one interactive control. It remains a client component only for the
 * confirmation step's open/closed state; the listing itself and the mutation
 * both live on the server, so neither the record nor the token is shipped.
 */
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={toggleCommodityProductStatus}>
      <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);
          formRef.current?.requestSubmit();
        }}
      />
    </form>
  );
}
