import type { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import { redirect } from "next/navigation";
import { eq } from "drizzle-orm";
import { Receipt, ShoppingCart } from "lucide-react";
import { Container } from "@/components/Container";
import { Breadcrumbs } from "@/components/Breadcrumbs";
import { requireUser } from "@/lib/auth/admin-guard";
import { db } from "@/lib/db/client";
import { users } from "@/lib/db/schema";
import { formatMinor, loadCartSummary } from "@/lib/store/cart";
import { CheckoutForm } from "./CheckoutForm";

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

export const dynamic = "force-dynamic";

export default async function CheckoutPage() {
  const session = await requireUser();
  const sessionUser = session.user as {
    id?: string;
    name?: string | null;
    email?: string | null;
  };

  const cart = await loadCartSummary();
  if (cart.items.length === 0) redirect("/products/store/cart");

  const [row] = sessionUser.id
    ? await db
        .select({
          name: users.name,
          email: users.email,
          country: users.country,
        })
        .from(users)
        .where(eq(users.id, sessionUser.id))
        .limit(1)
    : [];

  const shippingMinor = cart.subtotalMinor >= 100_00 ? 0 : 7_00;
  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", href: "/products/store/cart" },
              { label: "Checkout" },
            ]}
          />
          <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)]">
            <Receipt className="h-3 w-3" aria-hidden />
            Checkout
          </div>
          <h1 className="mt-4 font-display text-[34px] md:text-[44px] font-extrabold leading-[1.05] tracking-[-0.02em] text-[var(--color-ink)]">
            Confirm your order.
          </h1>
          <p className="mt-3 max-w-2xl text-[15px] leading-relaxed text-[var(--color-slate)]">
            We&rsquo;ll send you a formal invoice with the final total
            (including exact shipping) within two working days. Nothing is
            charged at this step — you pay against the invoice.
          </p>

          <div className="mt-10 grid gap-10 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
            <div>
              <h2 className="font-display text-[18px] font-extrabold text-[var(--color-ink)]">
                Shipping &amp; contact
              </h2>
              <div className="mt-4 rounded-2xl border border-[var(--color-line)] bg-white p-6">
                <CheckoutForm
                  defaultName={row?.name ?? sessionUser.name ?? ""}
                  defaultEmail={row?.email ?? sessionUser.email ?? ""}
                  defaultCountry={row?.country ?? ""}
                />
              </div>
              <div className="mt-4 text-[13px] text-[var(--color-slate)]">
                Need to change anything?{" "}
                <Link
                  href="/products/store/cart"
                  className="font-semibold text-[var(--color-blue)] hover:underline"
                >
                  Back to cart
                </Link>
              </div>
            </div>

            <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="flex items-center gap-2 font-display text-[18px] font-extrabold text-[var(--color-ink)]">
                  <ShoppingCart className="h-4 w-4 text-[var(--color-blue)]" aria-hidden />
                  Your order
                </h2>
                <ul className="space-y-3">
                  {cart.items.map((i) => (
                    <li
                      key={i.productId}
                      className="flex items-start gap-3 rounded-lg border border-[var(--color-line)] bg-white p-3 text-[13px]"
                    >
                      <div className="relative h-14 w-14 shrink-0 overflow-hidden rounded-md bg-[var(--color-mist)]">
                        {i.coverImage && (
                          <Image
                            src={i.coverImage}
                            alt=""
                            fill
                            sizes="56px"
                            className="object-cover"
                          />
                        )}
                      </div>
                      <div className="min-w-0 flex-1">
                        <div className="truncate font-semibold text-[var(--color-ink)]">
                          {i.title}
                        </div>
                        <div className="text-[12px] text-[var(--color-slate)]">
                          {i.quantity} × {formatMinor(i.priceMinor, i.currency)}
                        </div>
                      </div>
                      <div className="shrink-0 font-semibold text-[var(--color-ink)]">
                        {formatMinor(i.lineTotalMinor, i.currency)}
                      </div>
                    </li>
                  ))}
                </ul>
                <dl className="space-y-2 border-t border-[var(--color-line)] pt-3 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)]">
                      Estimated total
                    </dt>
                    <dd className="font-display text-[18px] font-extrabold text-[var(--color-ink)]">
                      {formatMinor(totalMinor, cart.currency)}
                    </dd>
                  </div>
                </dl>
              </div>
            </aside>
          </div>
        </div>
      </Container>
    </section>
  );
}
