"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";

type Destination = { city: string; state: string; label?: string };

type Props = {
  slug: string;
  unit: string;
  destinations: Destination[];
  currentCity: string | null;
  quantity: string;
  /**
   * When set, the form also offers to book the whole quantity as an RFQ without
   * choosing sizes — the buyer who just wants "500 MT, sizes to be confirmed".
   */
  productId?: number;
  minOrderQty?: number;
};

/**
 * Re-prices the product for a destination. The freight leg of the F.O.R price
 * is a transporter rate keyed on state + city, so the selection is pushed to the
 * URL and the server recalculates with it.
 *
 * The push runs inside a transition: the same route is re-rendered with new
 * search params rather than remounted, so a plain `pending` flag set before the
 * push had nothing to clear it and the button stayed on "Updating…" forever.
 */
export default function ForPriceForm({
  slug,
  unit,
  destinations,
  currentCity,
  quantity: initialQuantity,
  productId,
  minOrderQty = 0,
}: Props) {
  const router = useRouter();
  const [quantity, setQuantity] = useState(initialQuantity);
  const [city, setCity] = useState(currentCity ?? "");
  const [error, setError] = useState<string | null>(null);
  const [pending, startTransition] = useTransition();

  const submit = (event: React.FormEvent) => {
    event.preventDefault();
    setError(null);

    const destination = destinations.find((item) => item.city === city);
    const params = new URLSearchParams();
    if (destination) {
      params.set("city", destination.city);
      params.set("state", destination.state);
    }
    if (quantity) params.set("qty", quantity);

    startTransition(() => {
      router.push(`/products/${slug}${params.size ? `?${params.toString()}` : ""}`, {
        scroll: false,
      });
      router.refresh();
    });
  };

  const requestQuote = () => {
    const qty = Number(quantity);
    if (!qty || qty <= 0) {
      setError("Please enter the total quantity you want to book.");
      return;
    }
    if (minOrderQty > 0 && qty < minOrderQty) {
      setError(`Minimum order quantity is ${minOrderQty} ${unit}.`);
      return;
    }

    const params = new URLSearchParams({ product_id: String(productId), qty: String(qty) });
    if (city) params.set("city", city);
    startTransition(() => router.push(`/rfq/new?${params.toString()}`));
  };

  return (
    <form onSubmit={submit} className="space-y-3">
      <div className="grid grid-cols-2 gap-3">
        <div>
          <label htmlFor="for-quantity" className="mb-1 block text-xs text-gray-500">
            Total Quantity ({unit})
          </label>
          <input
            id="for-quantity"
            type="number"
            min="1"
            inputMode="numeric"
            value={quantity}
            onChange={(event) => {
              setError(null);
              setQuantity(event.target.value);
            }}
            placeholder="e.g. 500"
            className="w-full rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm focus:border-[#CC1414] focus:outline-none"
          />
        </div>
        <div>
          <label htmlFor="for-city" className="mb-1 block text-xs text-gray-500">
            Delivery City
          </label>
          <select
            id="for-city"
            value={city}
            onChange={(event) => setCity(event.target.value)}
            className="w-full rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm focus:border-[#CC1414] focus:outline-none"
          >
            <option value="">Select city</option>
            {destinations.map((destination) => (
              <option key={`${destination.city}-${destination.state}`} value={destination.city}>
                {destination.label ?? destination.city}
              </option>
            ))}
          </select>
        </div>
      </div>

      {destinations.length === 0 && (
        <p className="text-xs text-gray-400">
          No transporter rates published for this product yet — freight will be quoted on your RFQ.
        </p>
      )}

      {error && (
        <p className="rounded-lg bg-red-50 px-3 py-2 text-xs font-medium text-[#CC1414]">{error}</p>
      )}

      <div className="flex flex-col gap-2 sm:flex-row">
        <button
          type="submit"
          disabled={pending}
          className="flex-1 rounded-lg bg-[#CC1414] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-[#a30f0f] disabled:opacity-60"
        >
          {pending ? "Updating…" : "Get Best F.O.R Price"}
        </button>

        {/* Book by total quantity when the sizes are not decided yet. */}
        {productId ? (
          <button
            type="button"
            onClick={requestQuote}
            disabled={pending}
            className="flex-1 rounded-lg border border-[#CC1414] bg-white px-4 py-2.5 text-sm font-semibold text-[#CC1414] transition hover:bg-red-50 disabled:opacity-60"
          >
            Request For Quotes
          </button>
        ) : null}
      </div>

      {productId ? (
        <p className="text-[11px] leading-relaxed text-gray-400">
          Booking the total quantity only — you can confirm the size-wise split with our team later.
        </p>
      ) : null}
    </form>
  );
}
