"use client";

import Image from "next/image";
import Link from "next/link";
import { useActionState, useEffect, useState } from "react";
import { getCheckoutQuote, submitCheckout, type CheckoutQuoteView } from "@/app/(store)/actions";

type Line = { id: string; name: string; variant: string; image: string | null; qty: number; total: number; mode: "READY_STOCK" | "PRE_ORDER"; window: string | null };
const fmt = (n: number) => `৳${n.toLocaleString("en-IN")}`;

function Field({ name, label, type = "text", defaultValue, auto, hint, error }: { name: string; label: string; type?: string; defaultValue?: string; auto?: string; hint?: string; error?: string }) {
  return (
    <div><label htmlFor={name} className="label">{label}</label>
      <input id={name} name={name} type={type} defaultValue={defaultValue} autoComplete={auto} required aria-invalid={!!error} aria-describedby={error ? `${name}-e` : undefined} className={`field ${error ? "border-rose" : ""}`} />
      {hint && !error && <p className="text-[12px] text-stone mt-1">{hint}</p>}
      {error && <p id={`${name}-e`} className="text-rose text-[13px] mt-1">{error}</p>}
    </div>
  );
}

export default function CheckoutForm({ districts, lines, methods, terms, splitAllowed, holdHours, prefill }: {
  districts: string[]; lines: Line[]; methods: { bkash: boolean; nagad: boolean; bank: boolean }; terms: string; splitAllowed: boolean; holdHours: number;
  prefill: { name: string; email: string; phone: string; address: string; district: string; area: string };
}) {
  const [state, action, pending] = useActionState(submitCheckout, null);
  const [district, setDistrict] = useState(prefill.district);
  const [plan, setPlan] = useState<"FULL" | "DEPOSIT" | "COD">("FULL");
  const [method, setMethod] = useState<"BKASH" | "NAGAD" | "BANK" | "COD">(methods.bkash ? "BKASH" : methods.nagad ? "NAGAD" : "BANK");
  const [split, setSplit] = useState(false);
  const [code, setCode] = useState("");
  const [applied, setApplied] = useState("");
  const [q, setQ] = useState<CheckoutQuoteView | null>(null);
  const [accept, setAccept] = useState(false);
  const err = (k: string) => state?.errors?.[k];

  useEffect(() => {
    let live = true;
    getCheckoutQuote({ district, plan, splitShipment: split, discountCode: applied || undefined }).then((r) => {
      if (!live) return;
      setQ(r);
      if (r.allowedPlans.length && !r.allowedPlans.includes(plan)) setPlan(r.allowedPlans[0]);
    });
    return () => { live = false; };
  }, [district, plan, split, applied]);

  useEffect(() => { if (plan === "COD") setMethod("COD"); else if (method === "COD") setMethod(methods.bkash ? "BKASH" : methods.nagad ? "NAGAD" : "BANK"); }, [plan]); // eslint-disable-line react-hooks/exhaustive-deps

  const quoteErrors = (q?.errors ?? []).filter((e) => district || e !== "Choose a delivery district.");
  return (
    <form action={action} className="wrap py-10 md:py-16 grid lg:grid-cols-12 gap-10 lg:gap-16">
      <div className="lg:col-span-7 space-y-12">
        <h1 className="font-display text-[48px] md:text-[72px] leading-none">Checkout</h1>

        <section aria-labelledby="h-contact" className="space-y-5">
          <h2 id="h-contact" className="font-display text-[28px]">Delivery details</h2>
          <div className="grid sm:grid-cols-2 gap-5">
            <Field error={err("customerName")} name="customerName" label="Full name" defaultValue={prefill.name} auto="name" />
            <Field error={err("phone")} name="phone" label="Mobile number" defaultValue={prefill.phone} auto="tel" hint="We call or message this number about delivery." />
          </div>
          <Field error={err("email")} name="email" type="email" label="Email" defaultValue={prefill.email} auto="email" />
          <Field error={err("address")} name="address" label="Full address" defaultValue={prefill.address} auto="street-address" hint="House, road, block and landmark." />
          <div className="grid sm:grid-cols-2 gap-5">
            <div><label htmlFor="district" className="label">District</label>
              <select id="district" name="district" required value={district} onChange={(e) => setDistrict(e.target.value)} className={`field ${err("district") ? "border-rose" : ""}`}>
                <option value="">Choose district</option>{districts.map((d) => <option key={d}>{d}</option>)}
              </select>{err("district") && <p className="text-rose text-[13px] mt-1">{err("district")}</p>}
            </div>
            <Field error={err("area")} name="area" label="Area or thana" defaultValue={prefill.area} />
          </div>
          <div><label htmlFor="instructions" className="label">Delivery instructions (optional)</label><textarea id="instructions" name="instructions" rows={2} maxLength={500} className="field-area" /></div>
        </section>

        {q?.mixed && (
          <fieldset className="space-y-3 border border-sand p-5">
            <legend className="font-display text-[24px] px-2">Your bag has ready-to-ship and pre-order items</legend>
            <label className="flex gap-3 items-start"><input type="radio" name="splitShipmentUI" checked={!split} onChange={() => setSplit(false)} className="mt-1.5" /><span><strong className="font-medium">Ship everything together.</strong> Your whole order is dispatched once the pre-order items arrive. One delivery fee.</span></label>
            {splitAllowed && <label className="flex gap-3 items-start"><input type="radio" name="splitShipmentUI" checked={split} onChange={() => setSplit(true)} className="mt-1.5" /><span><strong className="font-medium">Ship ready items now, pre-order items later.</strong> Two parcels and two delivery fees.</span></label>}
            <input type="hidden" name="splitShipment" value={split ? "on" : ""} />
          </fieldset>
        )}

        <fieldset className="space-y-4">
          <legend className="font-display text-[28px] mb-2">Payment</legend>
          {q && q.allowedPlans.length === 0 && <p className="text-rose">No payment option is available for this bag. <Link href="/contact" className="underline">Contact us</Link>.</p>}
          {(q?.allowedPlans ?? ["FULL"]).map((p) => (
            <label key={p} className="flex gap-3 items-start border border-sand p-4 has-[:checked]:border-ink cursor-pointer">
              <input type="radio" name="plan" value={p} checked={plan === p} onChange={() => setPlan(p as typeof plan)} className="mt-1.5" />
              <span>{p === "FULL" ? <><strong className="font-medium">Pay in full now</strong><br /><span className="text-stone text-[14px]">The whole amount by bKash, Nagad or bank transfer.</span></>
                : p === "DEPOSIT" ? <><strong className="font-medium">Pay a deposit now, balance later</strong><br /><span className="text-stone text-[14px]">Deposit applies to pre-order items; ready-to-ship items and delivery are paid now. The balance is due before dispatch.</span></>
                : <><strong className="font-medium">Cash on delivery</strong><br /><span className="text-stone text-[14px]">Ready-to-ship items only. We confirm your order by phone.</span></>}</span>
            </label>
          ))}
          {plan !== "COD" ? (
            <div className="grid sm:grid-cols-3 gap-3" role="radiogroup" aria-label="Payment method">
              {methods.bkash && <label className="border border-sand p-3 has-[:checked]:border-ink cursor-pointer"><input type="radio" name="method" value="BKASH" checked={method === "BKASH"} onChange={() => setMethod("BKASH")} className="mr-2" />bKash</label>}
              {methods.nagad && <label className="border border-sand p-3 has-[:checked]:border-ink cursor-pointer"><input type="radio" name="method" value="NAGAD" checked={method === "NAGAD"} onChange={() => setMethod("NAGAD")} className="mr-2" />Nagad</label>}
              {methods.bank && <label className="border border-sand p-3 has-[:checked]:border-ink cursor-pointer"><input type="radio" name="method" value="BANK" checked={method === "BANK"} onChange={() => setMethod("BANK")} className="mr-2" />Bank transfer</label>}
            </div>
          ) : <input type="hidden" name="method" value="COD" />}
          {plan !== "COD" && <p className="text-[14px] text-stone">After you place the order you’ll see where to send the money and enter the transaction ID. Your items are held for {holdHours} hours. Your order isn’t confirmed until our team verifies the payment.</p>}
        </fieldset>

        {q?.hasPreorder && (
          <section className="border border-sand p-5 space-y-3">
            <h2 className="font-display text-[24px]">Pre-order terms</h2>
            <p className="text-[14px] leading-relaxed text-stone">{terms}</p>
            <ul className="text-[14px]">{lines.filter((l) => l.mode === "PRE_ORDER").map((l) => <li key={l.id}>{l.name}: estimated dispatch {l.window}</li>)}</ul>
            <label className="flex gap-3 items-start"><input type="checkbox" name="acceptTerms" checked={accept} onChange={(e) => setAccept(e.target.checked)} className="mt-1.5" /><span>I have read and accept the pre-order terms and understand dispatch dates are estimates.</span></label>
          </section>
        )}
      </div>

      <aside className="lg:col-span-5 lg:sticky lg:top-28 self-start space-y-6" aria-label="Order summary">
        <h2 className="font-display text-[28px]">Summary</h2>
        <ul className="divide-y divide-sand border-y border-sand">
          {lines.map((l) => <li key={l.id} className="py-3 flex gap-3"><div className="relative w-14 aspect-portrait bg-linen shrink-0">{l.image && <Image src={l.image} alt="" fill sizes="56px" className="object-cover" />}</div><div className="flex-1 text-[14px]"><p>{l.name} × {l.qty}</p><p className="text-stone">{l.variant}{l.mode === "PRE_ORDER" ? " · Pre-order" : ""}</p></div><span className="text-[14px]">{fmt(l.total)}</span></li>)}
        </ul>
        <div className="flex gap-2"><label htmlFor="code" className="sr-only">Discount code</label><input id="code" value={code} onChange={(e) => setCode(e.target.value)} placeholder="Discount code" className="field" /><button type="button" className="btn-line" onClick={() => setApplied(code.trim())}>Apply</button></div>
        <input type="hidden" name="discountCode" value={applied} />
        {q && (
          <dl className="space-y-2 text-[15px]">
            <div className="flex justify-between"><dt>Subtotal</dt><dd>{fmt(q.subtotal)}</dd></div>
            {q.discount > 0 && <div className="flex justify-between"><dt>Discount ({q.discountApplied})</dt><dd>−{fmt(q.discount)}</dd></div>}
            <div className="flex justify-between"><dt>Delivery{q.zoneName ? ` (${q.zoneName})` : ""}</dt><dd>{district ? fmt(q.shipping) : "Choose district"}</dd></div>
            <div className="flex justify-between text-[18px] border-t border-sand pt-3"><dt>Total</dt><dd>{fmt(q.total)}</dd></div>
            <div className="flex justify-between font-medium"><dt>{plan === "COD" ? "Pay on delivery" : "Pay now"}</dt><dd>{plan === "COD" ? fmt(q.total) : fmt(q.dueNow)}</dd></div>
            {q.balance > 0 && plan !== "COD" && <div className="flex justify-between text-stone"><dt>Balance{q.balanceDueAt ? ` due by ${q.balanceDueAt}` : ""}</dt><dd>{fmt(q.balance)}</dd></div>}
            {q.zoneEta && <p className="text-stone text-[13px]">Delivery usually takes {q.zoneEta}.</p>}
          </dl>
        )}
        {quoteErrors.map((e) => <p key={e} role="alert" className="text-rose text-[14px]">{e}</p>)}
        {state?.message && <p role="alert" className="text-rose text-[14px]">{state.message}</p>}
        <button className="btn-solid w-full" disabled={pending || (q?.hasPreorder && !accept) || quoteErrors.length > 0 || !q?.allowedPlans.length}>{pending ? "Placing order…" : plan === "COD" ? "Place order" : "Place order and get payment details"}</button>
        {q?.hasPreorder && !accept && <p className="text-[13px] text-stone text-center">Accept the pre-order terms to continue.</p>}
      </aside>
    </form>
  );
}
