import type { Metadata } from "next";
import Image from "next/image";
import Link from "next/link";
import { loadCart } from "@/lib/cart";
import { setCartQty, removeCartItem } from "../actions";
import { taka } from "@/lib/money";
import { fmtWindow } from "@/lib/dates";
import { depositLabel } from "@/lib/preorder";

export const metadata: Metadata = { title: "Bag", robots: { index: false } };

export default async function CartPage() {
  const cart = await loadCart();
  const hasPre = cart.lines.some((l) => l.mode === "PRE_ORDER");
  const hasReady = cart.lines.some((l) => l.mode === "READY_STOCK");
  const blocked = cart.lines.some((l) => l.problem);
  if (!cart.lines.length) {
    return (
      <div className="wrap py-24 text-center">
        <h1 className="font-display text-[48px] md:text-[80px] leading-none">Your bag is empty</h1>
        <p className="text-stone mt-4">Pieces you add will wait here.</p>
        <div className="mt-8 flex justify-center gap-4"><Link href="/shop" className="btn-solid">Shop all</Link><Link href="/wishlist" className="btn-line">Saved items</Link></div>
      </div>
    );
  }
  return (
    <div className="wrap py-10 md:py-16">
      <h1 className="font-display text-[48px] md:text-[80px] leading-none mb-10">Bag</h1>
      <div className="grid lg:grid-cols-12 gap-10 lg:gap-16">
        <ul className="lg:col-span-8 divide-y divide-sand border-y border-sand">
          {cart.lines.map((l) => (
            <li key={l.itemId} className="py-6 grid grid-cols-[96px_1fr] md:grid-cols-[130px_1fr] gap-5">
              <Link href={`/products/${l.slug}`} className="relative block aspect-portrait bg-linen">{l.image && <Image src={l.image} alt={l.imageAlt} fill sizes="130px" className="object-cover" />}</Link>
              <div className="flex flex-col">
                <div className="flex justify-between gap-4"><Link href={`/products/${l.slug}`} className="text-[16px] hover:text-gilt">{l.name}</Link><span>{taka(l.lineTotal)}</span></div>
                <p className="text-stone text-[14px]">{l.variantLabel} · {taka(l.unitPrice)} each</p>
                {l.mode === "PRE_ORDER" && l.batch ? (
                  <p className="eyebrow-status mt-2">Pre-order · estimated dispatch {fmtWindow(l.batch.dispatchFrom, l.batch.dispatchTo)} · {depositLabel(l.batch)}</p>
                ) : <p className="text-[13px] text-stone mt-2">Ready to ship</p>}
                {l.problem && <p role="alert" className="text-rose text-[14px] mt-2">{l.problem}</p>}
                <div className="mt-auto pt-4 flex items-center gap-6">
                  <form action={setCartQty} className="flex items-center gap-2">
                    <input type="hidden" name="itemId" value={l.itemId} />
                    <label htmlFor={`q-${l.itemId}`} className="sr-only">Quantity</label>
                    <select id={`q-${l.itemId}`} name="qty" defaultValue={Math.min(l.qty, Math.max(1, l.maxQty))} className="h-10 border border-sand bg-paper px-2">{Array.from({ length: Math.max(1, l.maxQty) }, (_, i) => <option key={i + 1} value={i + 1}>{i + 1}</option>)}</select>
                    <button className="nav-type underline underline-offset-4 hover:text-gilt">Update</button>
                  </form>
                  <form action={removeCartItem}><input type="hidden" name="itemId" value={l.itemId} /><button className="nav-type underline underline-offset-4 hover:text-gilt">Remove</button></form>
                </div>
              </div>
            </li>
          ))}
        </ul>
        <aside className="lg:col-span-4 lg:sticky lg:top-28 self-start space-y-5">
          <div className="flex justify-between text-[16px]"><span>Subtotal</span><span>{taka(cart.subtotal)}</span></div>
          <p className="text-stone text-[14px]">Delivery fee, discounts and any deposit are worked out at checkout.</p>
          {hasPreorder(hasPre) && hasReady && (
            <p className="border border-sand p-4 text-[14px]">Your bag has ready-to-ship and pre-order items. At checkout you choose to ship everything together once the pre-order arrives, or in two parcels.</p>
          )}
          {hasPre && !hasReady && <p className="border border-sand p-4 text-[14px]">Pre-order items are dispatched in their batch’s estimated window. You’ll confirm the pre-order terms at checkout.</p>}
          <Link href={blocked ? "#" : "/checkout"} aria-disabled={blocked} className={`btn-solid w-full ${blocked ? "opacity-40 pointer-events-none" : ""}`}>Checkout</Link>
          <Link href="/shop" className="link-line block text-center">Continue shopping</Link>
        </aside>
      </div>
    </div>
  );
}
function hasPreorder(b: boolean) { return b; }
