"use client";

import Link from "next/link";
import { useConvexAuth } from "convex/react";
import { formatPrice } from "@repo/utils";
import { ProductCard } from "@/components/product/ProductCard";
import { SectionHeading } from "@/utils/common/heading/section_heading";
import { useWishlist } from "@/lib/wishlist";
import { WISHLIST_PATH } from "@/lib/wishlist/constants";
import type { WishlistItem } from "@/lib/wishlist/types";
import type { ProductCardProps } from "@/components/product/ProductCard";

const MAX_ITEMS = 5;

function wishlistItemToCardProps(item: WishlistItem): ProductCardProps | null {
  const { product, variant } = item;
  if (!product) return null;

  const activeVariant = variant ?? product.variants[0];
  const currentPrice = activeVariant?.price ?? 0;
  const compareAtPrice = activeVariant?.compareAtPrice;

  const priceDrop =
    item.priceWhenAdded > 0 && currentPrice < item.priceWhenAdded;

  return {
    brand: product.brand ?? "",
    name: product.name,
    price: formatPrice(currentPrice),
    compareAtPrice:
      compareAtPrice && compareAtPrice > currentPrice
        ? formatPrice(compareAtPrice)
        : undefined,
    imageSrc: product.images[0]?.url ?? "/placeholder-product.png",
    imageAlt: product.images[0]?.alt ?? product.name,
    url: `/shop/${product.parentCategorySlug}/${product.childCategorySlug}/${product.slug}`,
    rating: product.averageRating ?? 0,
    reviewCount: product.reviewCount ?? 0,
    badge: priceDrop ? "sale" : undefined,
    productId: product._id,
    variantId: activeVariant?._id,
  };
}

export function WishlistSection() {
  const { isAuthenticated } = useConvexAuth();
  const { items, isLoading, isEmpty } = useWishlist();

  if (!isAuthenticated || isLoading || isEmpty) return null;

  const cards = items
    .slice(0, MAX_ITEMS)
    .map(wishlistItemToCardProps)
    .filter((c): c is ProductCardProps => c !== null);

  if (cards.length === 0) return null;

  return (
    <section aria-label="Your wishlist" className="w-full py-10 md:py-12">
      <div className="mx-auto max-w-7xl min-w-0 px-4 md:px-6">
        <div className="mb-6 flex flex-row flex-wrap items-center justify-between gap-4 md:mb-8">
          <SectionHeading title="Your Wishlist" />
          <Link
            href={WISHLIST_PATH}
            className="inline-flex items-center gap-1 rounded font-sans text-sm font-bold text-[var(--accent)] hover:underline focus:outline-none focus:ring-2 focus:ring-[var(--accent)] focus:ring-offset-2"
          >
            View All
            <span aria-hidden>→</span>
          </Link>
        </div>

        <div
          className="flex gap-6 overflow-x-auto scroll-smooth scrollbar-hide pb-2 lg:grid lg:grid-cols-5 lg:overflow-visible lg:pb-0"
          style={{ scrollSnapType: "x proximity" }}
        >
          {cards.map((props) => (
            <div
              key={props.url}
              className="min-w-[280px] shrink-1 lg:min-w-0 lg:shrink"
              style={{ scrollSnapAlign: "start" }}
            >
              <ProductCard {...props} hideWishlistAction />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
