"use client";

import { useCallback, useState } from "react";
import { CircleGauge, Layers, Tags, Warehouse } from "lucide-react";
import type { ApiProductAttributes, ApiSellerProduct } from "@/lib/api/types";
import UpdateDialog from "./UpdateDialog";
import PriceForm from "./PriceForm";
import VariationForm from "./VariationForm";
import QualityForm from "./QualityForm";
import StockForm from "./StockForm";

export type UpdatePanel = "price" | "variation" | "quality" | "stock";

const META: Record<UpdatePanel, { label: string; icon: typeof Tags }> = {
  price: { label: "Update Price", icon: Tags },
  variation: { label: "Update Variation", icon: Layers },
  quality: { label: "Update Quality", icon: CircleGauge },
  stock: { label: "Update Stock", icon: Warehouse },
};

/**
 * One update action, rendered in the header of the card it belongs to — the
 * price button sits with the price, the stock button with the variations it
 * changes. Each button owns its own dialog, so no shared open/closed state has
 * to be threaded through the page.
 *
 * Only this piece is client-side: the forms seed from the product the server
 * already fetched and save through Server Actions, so no auth token reaches the
 * browser. Closing the dialog unmounts the form, which is what makes reopening
 * show the saved values rather than an abandoned draft.
 *
 * The price panel needs only the product, so it also works from a product
 * list (the seller dashboard's quick price update).
 */
type UpdateButtonProps = {
  product: ApiSellerProduct;
  /** `ghost` for the secondary action when a card carries two. */
  variant?: "solid" | "ghost";
  /** After a successful save, for lists the action's revalidation does not refresh. */
  onSaved?: () => void;
} & (
  | { panel: "price"; attributes?: ApiProductAttributes }
  | { panel: Exclude<UpdatePanel, "price">; attributes: ApiProductAttributes }
);

export default function UpdateButton(props: UpdateButtonProps) {
  const { panel, product, variant = "solid", onSaved } = props;
  const [open, setOpen] = useState(false);
  const close = useCallback(() => setOpen(false), []);
  const done = useCallback(() => {
    setOpen(false);
    onSaved?.();
  }, [onSaved]);
  const { label, icon: Icon } = META[panel];

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        className={`inline-flex shrink-0 items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium transition ${
          variant === "solid"
            ? "bg-[#CC1414] text-white hover:bg-[#a30f0f]"
            : "border border-gray-200 text-gray-700 hover:border-[#CC1414] hover:text-[#CC1414]"
        }`}
      >
        <Icon className="h-3.5 w-3.5" />
        {label}
      </button>

      <UpdateDialog open={open} title={label} subtitle={product.name} onClose={close}>
        {props.panel === "price" && (
          <PriceForm
            id={product.id}
            defaults={{
              base_price: product.base_price ? String(product.base_price) : "",
              load_within: product.load_within ?? "",
              quantity: product.quantity ?? "",
              price_validity: product.price_validity ?? "",
            }}
            onDone={done}
          />
        )}
        {props.panel === "variation" && (
          <VariationForm id={product.id} variants={props.attributes.variants} onDone={done} />
        )}
        {props.panel === "quality" && (
          <QualityForm id={product.id} qualities={props.attributes.qualities} onDone={done} />
        )}
        {props.panel === "stock" && (
          <StockForm id={product.id} variants={props.attributes.variants} onDone={done} />
        )}
      </UpdateDialog>
    </>
  );
}
