"use client";

import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import {
  BadgeCheck,
  Heart,
  RefreshCw,
  ShieldCheck,
  Truck,
} from "lucide-react";
import { ProductGallery } from "@/components/product/ProductGallery";
import { ProductInfoTabs } from "@/components/product/ProductInfoTabs";
import { RelatedProducts } from "@/components/product/RelatedProducts";
import { ReviewsList } from "@/components/product/ReviewsList";
import { VariantSelector } from "@/components/product/VariantSelector";
import { PageShell } from "@/components/layout/PageShell";
import { Button } from "@/components/ui/Button";
import { StarRating } from "@/components/ui/StarRating";
import { useCart } from "@/context/cart-context";
import { useWishlist } from "@/context/wishlist-context";
import type { Product, Review } from "@/data/types";
import { discountPercent, formatPrice } from "@/lib/format";
import { easeOut } from "@/lib/motion";
import { motion } from "framer-motion";

export function ProductDetailView({
  product,
  related,
  reviews,
}: {
  product: Product;
  related: Product[];
  reviews: Review[];
}) {
  const router = useRouter();
  const { addItem } = useCart();
  const { toggle, has } = useWishlist();

  const initialSelected = useMemo(() => {
    const map: Record<string, string> = {};
    product.variants.forEach((variant) => {
      map[variant.id] = variant.options[0];
    });
    return map;
  }, [product]);

  const [selected, setSelected] = useState(initialSelected);
  const [qty, setQty] = useState(1);

  const variantLabel = Object.values(selected).join(" / ");
  const off = discountPercent(product.price, product.compareAt);

  const addToCart = () => addItem(product, qty, variantLabel);
  const buyNow = () => {
    addItem(product, qty, variantLabel, { openDrawer: false });
    router.push("/checkout");
  };

  return (
    <PageShell
      crumbs={[
        { label: "Home", href: "/" },
        { label: "Shop", href: "/shop" },
        {
          label: product.category,
          href: `/categories/${product.categorySlug}`,
        },
        { label: product.name },
      ]}
    >
      <div className="grid gap-10 lg:grid-cols-[1.05fr_0.95fr] lg:gap-14">
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.35, ease: easeOut }}
        >
          <ProductGallery images={product.images} name={product.name} />
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.35, delay: 0.04, ease: easeOut }}
        >
          <div>
            <div className="flex flex-wrap items-center gap-2">
              <p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted">
                {product.category}
              </p>
              {product.verified ? (
                <span className="inline-flex items-center gap-1 border border-border px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.12em] text-muted">
                  <BadgeCheck className="h-3 w-3" />
                  Verified
                </span>
              ) : null}
              {off > 0 ? (
                <span className="bg-[var(--accent)] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.12em] text-white">
                  −{off}%
                </span>
              ) : null}
            </div>

            <h1 className="font-display mt-3 text-3xl leading-none sm:text-4xl">
              {product.name}
            </h1>

            <div className="mt-3 flex flex-wrap items-center gap-3">
              <StarRating rating={product.rating} />
              <span className="text-sm text-muted">
                {product.rating} · {product.reviewCount} reviews
              </span>
              <span className="text-sm text-muted">· {product.seller}</span>
            </div>

            <div className="mt-5 flex items-end gap-3">
              <p className="font-display text-3xl tabular-nums leading-none">
                {formatPrice(product.price)}
              </p>
              {product.compareAt ? (
                <p className="mb-1 text-base text-muted line-through tabular-nums">
                  {formatPrice(product.compareAt)}
                </p>
              ) : null}
            </div>

            <p className="mt-5 text-[15px] leading-relaxed text-muted">
              {product.shortDescription}
            </p>
            <p className="mt-2 text-sm text-foreground/80">
              <span className="font-medium">Fit:</span> {product.fit}
            </p>

            <div className="mt-8 border border-border bg-card p-5 sm:p-6">
              {product.bestSeller ? (
                <p className="mb-4 text-[11px] font-semibold uppercase tracking-[0.12em] text-muted">
                  Bestseller
                </p>
              ) : null}
              <p className="mb-4 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted">
                {product.gender === "unisex"
                  ? "UNISEX"
                  : product.gender.toUpperCase()}
              </p>
              <VariantSelector
                variants={product.variants}
                selected={selected}
                onChange={(variantId, option) =>
                  setSelected((current) => ({
                    ...current,
                    [variantId]: option,
                  }))
                }
              />
              {product.sizeGuide.length > 0 ? (
                <a
                  href="#product-details"
                  className="mt-3 inline-block text-xs font-medium text-muted underline-offset-2 hover:text-foreground hover:underline"
                >
                  View size guide & measurements
                </a>
              ) : null}

              <div className="mt-5 flex flex-wrap items-center gap-3">
                <label className="sr-only" htmlFor="qty">
                  Quantity
                </label>
                <select
                  id="qty"
                  value={qty}
                  onChange={(event) => setQty(Number(event.target.value))}
                  className="h-11 border border-border bg-background px-3 text-sm"
                >
                  {[1, 2, 3, 4, 5].map((value) => (
                    <option key={value} value={value}>
                      Qty {value}
                    </option>
                  ))}
                </select>
              </div>

              <div className="mt-4 grid gap-3">
                <Button
                  onClick={addToCart}
                  disabled={product.stock <= 0}
                  className="h-12 w-full rounded-none"
                >
                  ADD TO CART
                </Button>
                <div className="flex gap-3">
                  <button
                    type="button"
                    onClick={() => toggle(product)}
                    className="inline-flex h-12 flex-1 items-center justify-center gap-2 border border-border text-sm font-semibold uppercase tracking-wide transition hover:bg-surface"
                    aria-label="Toggle wishlist"
                  >
                    <Heart
                      className={`h-4 w-4 ${has(product.id) ? "fill-current" : ""}`}
                    />
                    Add to wish list
                  </button>
                  <button
                    type="button"
                    onClick={buyNow}
                    disabled={product.stock <= 0}
                    className="inline-flex h-12 flex-1 items-center justify-center border border-border text-sm font-semibold uppercase tracking-wide transition hover:bg-surface disabled:opacity-50"
                  >
                    Buy now
                  </button>
                </div>
              </div>

              <p className="mt-4 text-sm text-muted">
                {product.stock > 0
                  ? `${product.stock} in stock · ships within 24h`
                  : "Currently unavailable"}
              </p>
            </div>

            <div className="mt-6 grid gap-3 sm:grid-cols-3">
              {[
                {
                  icon: Truck,
                  title: "FREE shipping $99+",
                  text: "Or paid standard $9",
                },
                {
                  icon: RefreshCw,
                  title: "Easy exchanges",
                  text: "30-day window",
                },
                {
                  icon: ShieldCheck,
                  title: "Secure checkout",
                  text: "Stripe protected",
                },
              ].map((item) => (
                <div
                  key={item.title}
                  className="rounded-none border border-border bg-[var(--paper)] px-3 py-3"
                >
                  <item.icon className="h-4 w-4 text-foreground" />
                  <p className="mt-2 text-sm font-semibold">{item.title}</p>
                  <p className="text-xs text-muted">{item.text}</p>
                </div>
              ))}
            </div>

            <div className="mt-8 border-t border-border pt-6">
              <h2 className="text-sm font-semibold uppercase tracking-[0.14em] text-muted">
                Quick essentials
              </h2>
              <ul className="mt-4 grid gap-2 sm:grid-cols-2">
                {product.details.map((detail) => (
                  <li
                    key={detail}
                    className="flex items-start gap-2 text-sm text-foreground"
                  >
                    <BadgeCheck className="mt-0.5 h-4 w-4 shrink-0" />
                    {detail}
                  </li>
                ))}
                <li className="flex items-start gap-2 text-sm text-foreground">
                  <BadgeCheck className="mt-0.5 h-4 w-4 shrink-0" />
                  Material: {product.materials[0]}
                </li>
                <li className="flex items-start gap-2 text-sm text-foreground">
                  <BadgeCheck className="mt-0.5 h-4 w-4 shrink-0" />
                  Seller: {product.seller}
                </li>
              </ul>
            </div>
          </div>
        </motion.div>
      </div>

      <div id="product-details" className="mt-4">
        <ProductInfoTabs product={product} />
      </div>

      <div className="mt-16">
        <h2 className="text-2xl font-semibold tracking-tight">
          Customer reviews
        </h2>
        <div className="mt-6">
          <ReviewsList reviews={reviews} />
        </div>
      </div>

      <RelatedProducts products={related} />
    </PageShell>
  );
}
