"use client";

import Image from "next/image";
import Link from "next/link";

import { QuantitySelector } from "@/components/cart/QuantitySelector";
import { useCart, type CartLine } from "@/components/cart/CartProvider";
import { EmptyState } from "@/components/ui";
import { formatPrice } from "@/lib/format";

/** The cart: line items with quantity controls, and the order summary. */
export function CartView() {
  const { lines, itemCount, subtotal, setQuantity, removeItem, clear, hydrated } = useCart();

  if (!hydrated) {
    return (
      <div className="space-y-4" aria-busy="true">
        {[0, 1].map((index) => (
          <div key={index} className="h-32 animate-pulse rounded-2xl bg-slate-200" />
        ))}
        <p className="sr-only">Loading your cart</p>
      </div>
    );
  }

  if (lines.length === 0) {
    return (
      <EmptyState
        title="Your cart is empty"
        description="Browse the catalogue and add something you like. Searching by meaning is the fastest way to find it."
        icon={
          <svg viewBox="0 0 24 24" className="size-6" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden="true">
            <path d="M3 4h2l2.4 11.2a2 2 0 0 0 2 1.6h7.7a2 2 0 0 0 2-1.6L21 8H6" />
            <circle cx="10" cy="20" r="1.4" />
            <circle cx="18" cy="20" r="1.4" />
          </svg>
        }
        action={
          <Link
            href="/products"
            className="inline-block rounded-lg bg-indigo-600 px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-indigo-700 focus-visible:ring-2 focus-visible:ring-indigo-600 focus-visible:ring-offset-2 focus-visible:outline-none"
          >
            Start shopping
          </Link>
        }
      />
    );
  }

  const shipping = subtotal >= 50 ? 0 : 5.99;
  const total = subtotal + shipping;

  return (
    <div className="grid gap-8 lg:grid-cols-[1fr_20rem]">
      <section aria-label="Cart items">
        <div className="space-y-4">
          {lines.map((line) => (
            <CartLineItem
              key={line.productId}
              line={line}
              onQuantityChange={(quantity) => setQuantity(line.productId, quantity)}
              onRemove={() => removeItem(line.productId)}
            />
          ))}
        </div>

        <div className="mt-6 flex flex-wrap items-center justify-between gap-3">
          <Link
            href="/products"
            className="text-sm font-semibold text-indigo-700 hover:text-indigo-900 focus-visible:ring-2 focus-visible:ring-indigo-600 focus-visible:outline-none"
          >
            ← Continue shopping
          </Link>
          <button
            type="button"
            onClick={clear}
            className="text-sm font-medium text-slate-500 underline-offset-2 hover:text-red-600 hover:underline focus-visible:ring-2 focus-visible:ring-indigo-600 focus-visible:outline-none"
          >
            Empty cart
          </button>
        </div>
      </section>

      <aside aria-label="Order summary">
        <div className="sticky top-24 space-y-4 rounded-2xl border border-slate-200 bg-white p-5">
          <h2 className="text-base font-semibold text-slate-900">Order summary</h2>

          <dl className="space-y-2 text-sm">
            <div className="flex justify-between">
              <dt className="text-slate-600">
                Items ({itemCount} {itemCount === 1 ? "unit" : "units"})
              </dt>
              <dd className="font-medium text-slate-900">{formatPrice(subtotal)}</dd>
            </div>
            <div className="flex justify-between">
              <dt className="text-slate-600">Shipping</dt>
              <dd className="font-medium text-slate-900">
                {shipping === 0 ? "Free" : formatPrice(shipping)}
              </dd>
            </div>
            <div className="flex justify-between border-t border-slate-200 pt-3 text-base">
              <dt className="font-semibold text-slate-900">Total</dt>
              <dd className="font-bold text-slate-900">{formatPrice(total)}</dd>
            </div>
          </dl>

          {subtotal < 50 ? (
            <p className="rounded-lg bg-amber-50 px-3 py-2 text-xs text-amber-800">
              Spend {formatPrice(50 - subtotal)} more for free shipping.
            </p>
          ) : null}

          <button
            type="button"
            disabled
            title="Checkout is out of scope for this demo"
            className="w-full cursor-not-allowed rounded-xl bg-slate-200 px-4 py-3 text-sm font-semibold text-slate-500"
          >
            Checkout (demo only)
          </button>
          <p className="text-center text-xs text-slate-500">
            This cart is stored in your browser only.
          </p>
        </div>
      </aside>
    </div>
  );
}

function CartLineItem({
  line,
  onQuantityChange,
  onRemove,
}: {
  line: CartLine;
  onQuantityChange: (quantity: number) => void;
  onRemove: () => void;
}) {
  return (
    <article className="flex gap-4 rounded-2xl border border-slate-200 bg-white p-4">
      <Link
        href={`/products/${line.productId}`}
        className="relative size-24 shrink-0 overflow-hidden rounded-xl bg-slate-100 focus-visible:ring-2 focus-visible:ring-indigo-600 focus-visible:outline-none"
      >
        <Image src={line.image} alt={line.name} fill sizes="96px" className="object-cover" />
      </Link>

      <div className="flex min-w-0 flex-1 flex-col gap-2">
        <div className="flex items-start justify-between gap-3">
          <div className="min-w-0">
            <h3 className="truncate text-sm font-semibold text-slate-900">
              <Link
                href={`/products/${line.productId}`}
                className="hover:text-indigo-700 focus-visible:ring-2 focus-visible:ring-indigo-600 focus-visible:outline-none"
              >
                {line.name}
              </Link>
            </h3>
            <p className="text-xs text-slate-500">{line.brand}</p>
          </div>
          <p className="shrink-0 text-sm font-bold text-slate-900">
            {formatPrice(line.price * line.quantity)}
          </p>
        </div>

        <div className="flex flex-wrap items-center justify-between gap-3">
          <QuantitySelector
            value={line.quantity}
            onChange={onQuantityChange}
            max={line.maxStock}
            size="sm"
          />
          <div className="flex items-center gap-3">
            <span className="text-xs text-slate-500">{formatPrice(line.price)} each</span>
            <button
              type="button"
              onClick={onRemove}
              className="text-xs font-medium text-slate-500 underline-offset-2 hover:text-red-600 hover:underline focus-visible:ring-2 focus-visible:ring-indigo-600 focus-visible:outline-none"
            >
              Remove
              <span className="sr-only"> {line.name} from cart</span>
            </button>
          </div>
        </div>

        {line.quantity >= line.maxStock ? (
          <p className="text-xs text-amber-700">Maximum available stock reached.</p>
        ) : null}
      </div>
    </article>
  );
}
