"use client";

import { useActionState, useEffect, useState } from "react";
import { toast } from "sonner";
import { updateProductPriceVisibility } from "./actions";
import { INITIAL_UPDATE_STATE, SubmitButton } from "./updates/shared";

type Props = {
  productId: number;
  /** Used to invalidate the public product page when a price is hidden. */
  slug: string | null;
  showBasicPrice: boolean;
  showExPrice: boolean;
  showForPrice: boolean;
  showFobPrice: boolean;
};

function Row({
  name,
  title,
  description,
  checked,
  onChange,
  fieldsKey,
}: {
  name: string;
  title: string;
  description: string;
  checked: boolean;
  onChange: (next: boolean) => void;
  /** Bumped after every save; see the note on the remount below. */
  fieldsKey: number;
}) {
  return (
    <label className="flex cursor-pointer items-start justify-between gap-4 rounded-lg border border-gray-200 p-3 hover:border-gray-300">
      <span className="min-w-0">
        <span className="block text-sm font-medium text-gray-900">{title}</span>
        <span className="mt-0.5 block text-xs text-gray-500">{description}</span>
      </span>
      {/*
        An unchecked checkbox sends nothing at all, so the action reads every
        switch as `=== "on"` and treats a missing key as off. That keeps the
        three states in one submit rather than three separate flags.
      */}
      <input
        key={`${name}-${fieldsKey}`}
        type="checkbox"
        name={name}
        checked={checked}
        onChange={(e) => onChange(e.target.checked)}
        className="mt-0.5 h-4 w-4 shrink-0 rounded border-gray-300 text-[#CC1414] focus:ring-[#CC1414]"
      />
    </label>
  );
}

/**
 * The four prices a buyer can be shown, and whether this listing shows them.
 *
 * Held as local state rather than left uncontrolled, so the switches survive the
 * form reset React performs when the server action settles — the same reason the
 * F.O.R fields elsewhere on this page are remounted after a save.
 */
export default function PriceVisibilityForm({
  productId,
  slug,
  showBasicPrice,
  showExPrice,
  showForPrice,
  showFobPrice,
}: Props) {
  const [state, formAction] = useActionState(updateProductPriceVisibility, INITIAL_UPDATE_STATE);

  const [basic, setBasic] = useState(showBasicPrice);
  const [ex, setEx] = useState(showExPrice);
  const [forPrice, setForPrice] = useState(showForPrice);
  const [fob, setFob] = useState(showFobPrice);

  /* Reseed from the saved product after a revalidate, so the switches report
     what was stored rather than what was last clicked. */
  useEffect(() => setBasic(showBasicPrice), [showBasicPrice]);
  useEffect(() => setEx(showExPrice), [showExPrice]);
  useEffect(() => setForPrice(showForPrice), [showForPrice]);
  useEffect(() => setFob(showFobPrice), [showFobPrice]);

  useEffect(() => {
    if (!state.message) return;
    if (state.ok) toast.success(state.message);
    else toast.error(state.message);
  }, [state]);

  /*
    React resets the <form> once a server action settles, which puts every
    checkbox back to the value it was first rendered with — the DOM ends up
    disagreeing with the state that drives it, and because that state is already
    what the seller clicked, no re-render follows to correct it. So the switches
    looked untouched until a refresh re-mounted them from the saved product.

    Remounting the inputs is the same fix the F.O.R fields below use, and it
    re-applies all three from state rather than from the reset DOM.
  */
  const [fieldsKey, setFieldsKey] = useState(0);
  useEffect(() => {
    if (state.ok) setFieldsKey((n) => n + 1);
  }, [state]);

  return (
    <form action={formAction} className="space-y-3">
      <input type="hidden" name="id" value={productId} />
      {slug ? <input type="hidden" name="slug" value={slug} /> : null}

      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <Row
          name="show_basic_price"
          title="Show Basic Price"
          description="Buyers see the basic rate, before loading, insurance and taxes."
          checked={basic}
          onChange={setBasic}
          fieldsKey={fieldsKey}
        />
        <Row
          name="show_ex_price"
          title="Show Ex Price"
          description="Buyers see the Ex-Works line in the price breakup."
          checked={ex}
          onChange={setEx}
          fieldsKey={fieldsKey}
        />
        <Row
          name="show_for_price"
          title="Show F.O.R Price"
          description="Buyers see the delivered (doorstep) price for their city."
          checked={forPrice}
          onChange={setForPrice}
          fieldsKey={fieldsKey}
        />
        <Row
          name="show_fob_price"
          title="Show F.O.B Price"
          description="No F.O.B price is published yet — this reserves the switch for it."
          checked={fob}
          onChange={setFob}
          fieldsKey={fieldsKey}
        />
      </div>

      <div className="flex flex-wrap items-center justify-between gap-3">
        <p className="text-xs text-gray-500">
          With all four off, buyers see “On Request” instead of a price.
        </p>
        <SubmitButton label="Save visibility" />
      </div>
    </form>
  );
}
