"use client";

import { useEffect, useState, type ReactNode } from "react";

type Mode = "total" | "variants";

type Props = {
  /** Book a total quantity when the size split is not decided yet. */
  totalQuantity: ReactNode;
  /** Pick sizes and quantities row by row. */
  variants: ReactNode;
  /** Which tab opens first — "total" once a quantity or city is in the URL. */
  defaultMode?: Mode;
};

/**
 * The two ways into an RFQ, one or the other rather than both at once: a buyer
 * either books a total quantity ("500 MT, sizes to follow") or picks the sizes.
 * Showing both stacked made the page read as if the size table were required.
 */
export default function RfqModeTabs({
  totalQuantity,
  variants,
  defaultMode = "variants",
}: Props) {
  const [mode, setMode] = useState<Mode>(defaultMode);

  /* "Check F.O.R Price" links here; open the tab that actually holds the form
     rather than dropping the buyer on the size table. */
  useEffect(() => {
    const openFromHash = () => {
      if (window.location.hash === "#get-best-price") setMode("total");
    };
    openFromHash();
    window.addEventListener("hashchange", openFromHash);
    return () => window.removeEventListener("hashchange", openFromHash);
  }, []);

  const tabClass = (active: boolean) =>
    `flex-1 rounded-lg px-4 py-2 text-xs font-semibold transition sm:flex-none ${
      active
        ? "bg-[#CC1414] text-white shadow-sm"
        : "bg-white text-gray-600 hover:text-[#CC1414]"
    }`;

  return (
    <div id="get-best-price" className="scroll-mt-28">
      <div
        role="tablist"
        aria-label="How do you want to raise this RFQ?"
        className="mb-5 flex gap-1 rounded-xl border border-gray-200 bg-gray-50 p-1"
      >
        <button
          type="button"
          role="tab"
          aria-selected={mode === "total"}
          onClick={() => setMode("total")}
          className={tabClass(mode === "total")}
        >
          Total Quantity
        </button>
        <button
          type="button"
          role="tab"
          aria-selected={mode === "variants"}
          onClick={() => setMode("variants")}
          className={tabClass(mode === "variants")}
        >
          Select Sizes
        </button>
      </div>

      <div role="tabpanel" hidden={mode !== "total"}>
        {totalQuantity}
      </div>
      <div role="tabpanel" hidden={mode !== "variants"}>
        {variants}
      </div>
    </div>
  );
}
