"use client";

import { SafeImage } from "@/components/ui/SafeImage";
import Link from "next/link";
import { useState } from "react";
import { Lock } from "lucide-react";
import { PageShell } from "@/components/layout/PageShell";
import { Reveal } from "@/components/motion/Reveal";
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { useCart } from "@/context/cart-context";
import { formatPrice } from "@/lib/format";

export default function CartPage() {
  const {
    items,
    subtotal,
    discount,
    shipping,
    total,
    coupon,
    updateQuantity,
    removeItem,
    applyCoupon,
    clearCoupon,
  } = useCart();
  const [code, setCode] = useState("");

  return (
    <PageShell
      crumbs={[{ label: "Home", href: "/" }, { label: "Cart" }]}
      eyebrow="Bag"
      title="Your cart"
      description="Review items, apply a coupon, and continue to secure checkout."
    >
      {items.length === 0 ? (
        <Reveal className="rounded-[1.35rem] border border-border bg-card p-8">
          <p className="text-muted">Your cart is empty.</p>
          <Button href="/shop" className="mt-6">
            Continue shopping
          </Button>
        </Reveal>
      ) : (
        <div className="grid gap-8 lg:grid-cols-[1.4fr_0.85fr]">
          <Reveal>
            <ul className="space-y-4">
              {items.map((item) => (
                <li
                  key={`${item.product.id}-${item.variantLabel}`}
                  className="grid grid-cols-[88px_1fr] gap-4 rounded-[1.25rem] border border-border bg-card p-4 transition hover:border-foreground/20 sm:grid-cols-[112px_1fr_auto]"
                >
                  <div className="relative aspect-square overflow-hidden rounded-xl bg-surface">
                    <SafeImage
                      src={item.product.images[0]}
                      alt={item.product.name}
                      fill
                      sizes="112px"
                      className="object-cover"
                    />
                  </div>
                  <div>
                    <Link
                      href={`/product/${item.product.id}`}
                      className="font-medium tracking-tight hover:opacity-70"
                    >
                      {item.product.name}
                    </Link>
                    {item.variantLabel ? (
                      <p className="mt-1 text-sm text-muted">
                        {item.variantLabel}
                      </p>
                    ) : null}
                    <p className="mt-1 text-sm tabular-nums">
                      {formatPrice(item.product.price)}
                    </p>
                    <div className="mt-3 flex items-center gap-3">
                      <select
                        value={item.quantity}
                        onChange={(event) =>
                          updateQuantity(
                            item.product.id,
                            Number(event.target.value),
                            item.variantLabel,
                          )
                        }
                        className="h-9 rounded-full border border-border bg-background px-3 text-sm"
                      >
                        {[1, 2, 3, 4, 5, 6, 7, 8].map((value) => (
                          <option key={value} value={value}>
                            {value}
                          </option>
                        ))}
                      </select>
                      <button
                        type="button"
                        onClick={() =>
                          removeItem(item.product.id, item.variantLabel)
                        }
                        className="text-sm text-muted underline-offset-2 hover:underline"
                      >
                        Remove
                      </button>
                    </div>
                  </div>
                  <p className="hidden text-sm font-semibold tabular-nums sm:block">
                    {formatPrice(item.product.price * item.quantity)}
                  </p>
                </li>
              ))}
            </ul>
          </Reveal>

          <Reveal delay={0.05}>
            <aside className="h-fit rounded-[1.35rem] border border-border bg-card p-5 shadow-[0_16px_40px_rgba(10,10,10,0.04)] sm:p-6">
              <h2 className="text-lg font-semibold tracking-tight">
                Order summary
              </h2>
              <div className="mt-5 space-y-3 text-sm">
                <Row label="Subtotal" value={formatPrice(subtotal)} />
                <Row
                  label="Shipping"
                  value={shipping === 0 ? "Free" : formatPrice(shipping)}
                />
                {discount > 0 ? (
                  <Row label="Discount" value={`- ${formatPrice(discount)}`} />
                ) : null}
                <div className="border-t border-border pt-3">
                  <Row label="Total" value={formatPrice(total)} bold />
                </div>
              </div>

              <div className="mt-5 space-y-2">
                {coupon ? (
                  <div className="flex items-center justify-between rounded-2xl border border-border bg-background px-3 py-2 text-sm">
                    <span>{coupon.code}</span>
                    <button
                      type="button"
                      onClick={clearCoupon}
                      className="text-muted underline"
                    >
                      Remove
                    </button>
                  </div>
                ) : (
                  <div className="flex gap-2">
                    <Input
                      placeholder="Coupon code"
                      value={code}
                      onChange={(event) => setCode(event.target.value)}
                    />
                    <Button
                      variant="secondary"
                      onClick={() => {
                        if (applyCoupon(code)) setCode("");
                      }}
                    >
                      Apply
                    </Button>
                  </div>
                )}
                <p className="text-xs text-muted">Try FLIE10, WELCOME15 or SAVE200</p>
              </div>

              <Button href="/checkout" className="mt-6 w-full">
                <span className="inline-flex items-center gap-2">
                  <Lock className="h-3.5 w-3.5" />
                  Secure checkout
                </span>
              </Button>
            </aside>
          </Reveal>
        </div>
      )}
    </PageShell>
  );
}

function Row({
  label,
  value,
  bold,
}: {
  label: string;
  value: string;
  bold?: boolean;
}) {
  return (
    <div
      className={`flex items-center justify-between ${bold ? "font-semibold" : ""}`}
    >
      <span className={bold ? "" : "text-muted"}>{label}</span>
      <span className="tabular-nums">{value}</span>
    </div>
  );
}
