"use client";

import { useMemo, useState } from "react";
import { placeShopOrderAction } from "@/app/shop-actions";
import { orderTotal, type Shop, type ShopProduct } from "@/lib/shop";
import { shopCopy } from "@/lib/shop-ui";

export function ShopOrderForm({
  shop,
  product,
  error,
}: {
  shop: Shop;
  product: ShopProduct;
  error?: string;
}) {
  const copy = shopCopy(shop.locale);
  const available = product.sizes.filter((row) => row.qty > 0);
  const [size, setSize] = useState(available[0]?.label ?? "");
  const [qty, setQty] = useState(1);
  const total = useMemo(() => orderTotal(product, qty), [product, qty]);
  const selected = product.sizes.find((row) => row.label === size);
  const max = selected?.qty ?? 0;

  if (available.length === 0) {
    return <p className="rounded-2xl border border-white/20 p-4 text-sm">{copy.soldOut}</p>;
  }

  return (
    <form action={placeShopOrderAction} className="space-y-3">
      <input type="hidden" name="slug" value={shop.slug} />
      <input type="hidden" name="productId" value={product.id} />
      {error ? <p className="text-sm text-red-300">{copy.errors[error] ?? copy.errors.fields}</p> : null}
      <label className="block text-sm">
        {copy.size}
        <select name="size" value={size} onChange={(e) => setSize(e.target.value)} className="mt-1 w-full rounded-xl px-3 py-2 text-black">
          {available.map((row) => (
            <option key={row.label} value={row.label}>
              {row.label} — {copy.left.replace("{n}", String(row.qty))}
            </option>
          ))}
        </select>
      </label>
      <label className="block text-sm">
        {copy.qty}
        <input
          name="qty"
          type="number"
          min={1}
          max={max}
          value={qty}
          onChange={(e) => setQty(Math.max(1, Number(e.target.value) || 1))}
          className="mt-1 w-full rounded-xl px-3 py-2 text-black"
        />
      </label>
      <p className="text-lg font-bold">
        {copy.total}: {total} {shop.currency}
      </p>
      {product.offerQty > 1 && product.offerPrice > 0 ? (
        <p className="text-sm opacity-80">
          {copy.offer
            .replace("{n}", String(product.offerQty))
            .replace("{price}", String(product.offerPrice))
            .replace("{cur}", shop.currency)}
        </p>
      ) : null}
      <label className="block text-sm">
        {copy.name}
        <input name="buyerName" required className="mt-1 w-full rounded-xl px-3 py-2 text-black" />
      </label>
      <label className="block text-sm">
        {copy.phone}
        <input name="phone" required className="mt-1 w-full rounded-xl px-3 py-2 text-black" />
      </label>
      <label className="block text-sm">
        {copy.address}
        <textarea name="address" required rows={3} className="mt-1 w-full rounded-xl px-3 py-2 text-black" />
      </label>
      <label className="block text-sm">
        {copy.notes}
        <textarea name="notes" rows={2} className="mt-1 w-full rounded-xl px-3 py-2 text-black" />
      </label>
      <fieldset className="space-y-2 text-sm">
        <legend className="font-medium">{copy.pay}</legend>
        <label className="flex items-center gap-2">
          <input type="radio" name="paymentMethod" value="COD" defaultChecked />
          {copy.cod}
        </label>
        <label className="flex items-center gap-2">
          <input type="radio" name="paymentMethod" value="TRANSFER" />
          {copy.transfer}
        </label>
      </fieldset>
      {shop.paymentNote ? <p className="rounded-xl bg-black/20 p-3 text-sm">{shop.paymentNote}</p> : null}
      <button className="w-full rounded-full bg-white px-4 py-3 font-bold text-black">{copy.buy}</button>
    </form>
  );
}
