import type { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import {
  ArrowRight,
  ShoppingBag,
  ShoppingCart,
  Trash2,
} from "lucide-react";
import { Container } from "@/components/Container";
import { Button } from "@/components/Button";
import { Breadcrumbs } from "@/components/Breadcrumbs";
import { formatMinor, loadCartSummary } from "@/lib/store/cart";
import { updateCartLine, removeCartLine, clearCart } from "./actions";

export const metadata: Metadata = {
  title: "Cart — OrthoGlobe Store",
  robots: { index: false, follow: false },
};

export const dynamic = "force-dynamic";

export default async function CartPage() {
  const cart = await loadCartSummary();
  const shippingMinor = cart.subtotalMinor === 0 ? 0 : estimatedShipping(cart);
  const totalMinor = cart.subtotalMinor + shippingMinor;

  return (
    <section className="bg-white pt-10 pb-16 md:pt-14 md:pb-20">
      <Container>
        <div className="mx-auto max-w-5xl">
          <Breadcrumbs
            items={[
              { label: "Store", href: "/products/store" },
              { label: "Cart" },
            ]}
          />
          <div className="mt-6 inline-flex items-center gap-2 rounded-full border border-[var(--color-line)] bg-[var(--color-mist)] px-3 py-1 text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
            <ShoppingCart className="h-3 w-3" aria-hidden />
            Your cart
          </div>
          <h1 className="mt-4 font-display text-[34px] md:text-[44px] font-extrabold leading-[1.05] tracking-[-0.02em] text-[var(--color-ink)]">
            {cart.itemCount === 0
              ? "Your cart is empty."
              : `${cart.itemCount} item${cart.itemCount === 1 ? "" : "s"} in your cart.`}
          </h1>

          {cart.items.length === 0 ? (
            <div className="mt-10 rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-10 text-center">
              <ShoppingBag
                className="mx-auto h-8 w-8 text-[var(--color-slate)]"
                aria-hidden
              />
              <p className="mt-4 text-[15px] text-[var(--color-slate)]">
                Nothing here yet — browse the store to add products.
              </p>
              <div className="mt-5">
                <Button href="/products/store" variant="primary">
                  Browse the store
                </Button>
              </div>
            </div>
          ) : (
            <div className="mt-10 grid gap-8 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
              <ul className="space-y-4">
                {cart.items.map((i) => (
                  <li
                    key={i.productId}
                    className="flex flex-wrap items-start gap-4 rounded-2xl border border-[var(--color-line)] bg-white p-4 md:p-5"
                  >
                    <Link
                      href={`/products/store/${i.slug}`}
                      className="relative block h-24 w-24 shrink-0 overflow-hidden rounded-xl bg-[var(--color-mist)]"
                    >
                      {i.coverImage && (
                        <Image
                          src={i.coverImage}
                          alt=""
                          fill
                          sizes="96px"
                          className="object-cover"
                        />
                      )}
                    </Link>
                    <div className="min-w-0 flex-1">
                      <Link
                        href={`/products/store/${i.slug}`}
                        className="font-display text-[17px] font-extrabold text-[var(--color-ink)] hover:text-[var(--color-blue)]"
                      >
                        {i.title}
                      </Link>
                      <div className="mt-1 flex flex-wrap items-center gap-2 text-[12px] text-[var(--color-slate)]">
                        <span>{formatMinor(i.priceMinor, i.currency)} each</span>
                        {i.memberOnly && (
                          <span className="rounded-full bg-[var(--color-mist)] px-2 py-0.5 text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                            Members only
                          </span>
                        )}
                        {i.stockStatus === "preorder" && (
                          <span className="rounded-full bg-amber-50 px-2 py-0.5 text-[11px] font-bold uppercase tracking-wider text-amber-700">
                            Pre-order
                          </span>
                        )}
                      </div>

                      <div className="mt-4 flex flex-wrap items-center justify-between gap-3">
                        <form
                          action={updateCartLine}
                          className="flex items-center gap-2"
                        >
                          <input
                            type="hidden"
                            name="productId"
                            value={i.productId}
                          />
                          <label className="text-[12px] font-semibold text-[var(--color-slate)]">
                            Qty
                          </label>
                          <input
                            name="quantity"
                            type="number"
                            min={1}
                            max={100}
                            defaultValue={i.quantity}
                            className="w-16 rounded-md border border-[var(--color-line)] bg-white px-2 py-1 text-[13px] focus:border-[var(--color-blue)] focus:outline-none"
                          />
                          <button
                            type="submit"
                            className="rounded-md border border-[var(--color-line)] bg-white px-3 py-1 text-[12px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                          >
                            Update
                          </button>
                        </form>
                        <div className="flex items-center gap-3">
                          <span className="font-display text-[16px] font-extrabold text-[var(--color-ink)]">
                            {formatMinor(i.lineTotalMinor, i.currency)}
                          </span>
                          <form action={removeCartLine}>
                            <input
                              type="hidden"
                              name="productId"
                              value={i.productId}
                            />
                            <button
                              type="submit"
                              aria-label={`Remove ${i.title}`}
                              className="inline-flex items-center gap-1 rounded-md p-1.5 text-[var(--color-slate)] hover:bg-red-50 hover:text-red-600"
                            >
                              <Trash2 className="h-4 w-4" aria-hidden />
                            </button>
                          </form>
                        </div>
                      </div>
                    </div>
                  </li>
                ))}
                <li className="flex justify-end">
                  <form action={clearCart}>
                    <button
                      type="submit"
                      className="text-[12px] font-semibold text-[var(--color-slate)] underline hover:text-red-600"
                    >
                      Empty cart
                    </button>
                  </form>
                </li>
              </ul>

              <aside>
                <div className="sticky top-24 space-y-4 rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-6">
                  <h2 className="font-display text-[18px] font-extrabold text-[var(--color-ink)]">
                    Order summary
                  </h2>
                  <dl className="space-y-2 text-[14px]">
                    <div className="flex justify-between">
                      <dt className="text-[var(--color-slate)]">Subtotal</dt>
                      <dd className="font-semibold text-[var(--color-ink)]">
                        {formatMinor(cart.subtotalMinor, cart.currency)}
                      </dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="text-[var(--color-slate)]">Shipping (est.)</dt>
                      <dd className="font-semibold text-[var(--color-ink)]">
                        {shippingMinor === 0
                          ? "Free"
                          : formatMinor(shippingMinor, cart.currency)}
                      </dd>
                    </div>
                    <div className="flex justify-between border-t border-[var(--color-line)] pt-2">
                      <dt className="font-display text-[16px] font-extrabold text-[var(--color-ink)]">
                        Total
                      </dt>
                      <dd className="font-display text-[18px] font-extrabold text-[var(--color-ink)]">
                        {formatMinor(totalMinor, cart.currency)}
                      </dd>
                    </div>
                  </dl>
                  <div className="rounded-lg border border-[var(--color-line)] bg-white p-3 text-[12px] leading-relaxed text-[var(--color-slate)]">
                    Shipping is finalised on the invoice based on delivery
                    destination. You&rsquo;ll see a final total before anything
                    is charged.
                  </div>
                  <Link
                    href="/products/store/checkout"
                    className="inline-flex w-full items-center justify-center gap-2 rounded-lg bg-[var(--color-blue)] px-5 py-3 text-[14px] font-semibold text-white shadow-sm transition-opacity hover:opacity-95"
                  >
                    Continue to checkout
                    <ArrowRight className="h-4 w-4" aria-hidden />
                  </Link>
                  {cart.hasMemberOnly && (
                    <p className="text-[11px] leading-relaxed text-[var(--color-slate)]">
                      One or more items are members-only. Please sign in
                      before checkout.
                    </p>
                  )}
                </div>
              </aside>
            </div>
          )}
        </div>
      </Container>
    </section>
  );
}

/** Simple tiered shipping stub — admin finalises the real cost on invoice. */
function estimatedShipping(cart: Awaited<ReturnType<typeof loadCartSummary>>): number {
  if (cart.subtotalMinor === 0) return 0;
  // Free above £100 — flat £7 otherwise.
  if (cart.subtotalMinor >= 100_00) return 0;
  return 7_00;
}
