"use client";

import React, { useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { Star, ShoppingBag, Check } from "lucide-react";
import { addToCart } from "@/lib/cart";
import { toggleWishlist, isInWishlist } from "@/lib/wishlist";
import { useCurrency } from "@/providers/CurrencyProvider";
import { useSettings } from "@/providers/SettingsProvider";

interface Variant {
  id: string;
  size: string;
  color: string;
  length: string | null;
  stock: number;
  price: number | null;
}

interface Product {
  id: string;
  title: string;
  slug: string;
  description: string;
  thumbnail: string;
  basePrice: number;
  discountPrice: number | null;
  flashSaleEndDate?: string | Date | null;
  featured: boolean;
  brand?: { name: string } | null;
  category?: { name: string; slug: string } | null;
  variants: Variant[];
}

interface ProductCardProps {
  product: Product;
  idPrefix?: string;
  priority?: boolean;
  showBadges?: boolean;
}

export default function ProductCard({
  product,
  idPrefix = "product",
  priority = false,
  showBadges = true,
}: ProductCardProps) {
  const { formatPrice } = useCurrency();
  const { storeName } = useSettings();
  const [hovered, setHovered] = useState(false);
  const [selectedSize, setSelectedSize] = useState<string>("");
  const [selectedLength, setSelectedLength] = useState<string>("");
  const [wishlisted, setWishlisted] = useState(false);
  const [added, setAdded] = useState(false);
  const [timeLeft, setTimeLeft] = useState<string | null>(null);

  React.useEffect(() => {
    if (product.flashSaleEndDate) {
      const target = new Date(product.flashSaleEndDate).getTime();
      const interval = setInterval(() => {
        const now = new Date().getTime();
        const distance = target - now;
        if (distance < 0) {
          clearInterval(interval);
          setTimeLeft(null);
        } else {
          const days = Math.floor(distance / (1000 * 60 * 60 * 24));
          const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
          const seconds = Math.floor((distance % (1000 * 60)) / 1000);
          setTimeLeft(`${days}d ${hours}h ${minutes}m ${seconds}s`);
        }
      }, 1000);
      return () => clearInterval(interval);
    }
  }, [product.flashSaleEndDate]);

  React.useEffect(() => {
    setWishlisted(isInWishlist(product.id));
    const handleUpdate = () => setWishlisted(isInWishlist(product.id));
    window.addEventListener("wishlist-updated", handleUpdate);
    return () => window.removeEventListener("wishlist-updated", handleUpdate);
  }, [product.id]);

  // Extract unique sizes, lengths, and colors from variants
  const uniqueSizes = Array.from(new Set(product.variants.map((v) => v.size))).filter(Boolean);
  const uniqueLengths = Array.from(
    new Set(product.variants.filter((v) => v.length).map((v) => v.length))
  ) as string[];
  const uniqueColors = Array.from(new Set(product.variants.map((v) => v.color))).filter(Boolean);

  const primaryColor = uniqueColors[0] || "Classic";
  const additionalColorsCount = uniqueColors.length - 1;
  const colorLabel =
    additionalColorsCount > 0
      ? `${primaryColor}, +${additionalColorsCount} colors`
      : primaryColor;

  const originalPrice = product.basePrice;
  const discountPrice = product.discountPrice;
  const hasDiscount = discountPrice && discountPrice < originalPrice;

  const activePrice = hasDiscount ? (discountPrice as number) : originalPrice;

  const totalStock = product.variants.reduce((acc, v) => acc + v.stock, 0);
  const isOutOfStock = totalStock === 0;
  const isLowStock = totalStock > 0 && totalStock <= 5;

  const handleAddToCart = () => {
    const finalSize = selectedSize || uniqueSizes[0] || "";
    const finalLength = selectedLength || uniqueLengths[0] || "";
    const finalColor = primaryColor;

    addToCart({
      productId: product.id,
      slug: product.slug,
      title: product.title,
      thumbnail: product.thumbnail,
      color: finalColor,
      size: finalSize,
      length: finalLength,
      price: activePrice,
    });

    setAdded(true);
    // Reset after 1.8 s
    setTimeout(() => setAdded(false), 1800);
  };

  return (
    <div
      className="flex flex-col group bg-white border border-zinc-100/60 transition-all duration-300 rounded-sm overflow-hidden"
      id={`${idPrefix}-${product.id}`}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      {/* ── Thumbnail ── */}
      <div className="relative aspect-[3/4] bg-zinc-50 w-full overflow-hidden">
        <Link href={`/product/${product.slug}`} className="absolute inset-0 block z-0">
          <Image
            src={product.thumbnail}
            alt={product.title}
            fill
            sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
            className="object-cover group-hover:scale-[1.02] transition-transform duration-700 select-none"
          />
        </Link>

        {/* Wishlist bookmark */}
        <button
          onClick={(e) => {
            e.preventDefault();
            toggleWishlist({
              productId: product.id,
              slug: product.slug,
              title: product.title,
              thumbnail: product.thumbnail,
              basePrice: product.basePrice,
              discountPrice: product.discountPrice
            });
          }}
          className="absolute top-3 right-3 z-10 p-2 rounded-full bg-white/80 hover:bg-white shadow-sm transition-all duration-200 cursor-pointer"
          aria-label="Add to Wishlist"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            viewBox="0 0 24 24"
            fill={wishlisted ? "currentColor" : "none"}
            stroke="currentColor"
            strokeWidth="1.5"
            className={`w-4 h-4 transition-colors ${
              wishlisted ? "text-zinc-950 fill-zinc-950" : "text-zinc-500 hover:text-zinc-950"
            }`}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M17.593 3.322c1.1.128 1.907 1.077 1.907 2.185V21L12 17.25 4.5 21V5.507c0-1.108.806-2.057 1.907-2.185a48.507 48.507 0 0 1 11.186 0Z"
            />
          </svg>
        </button>

        {/* Badges — featured takes priority over sale */}
        {isOutOfStock ? (
          <span className="absolute top-3 left-3 bg-zinc-400 text-white text-[9px] font-bold tracking-widest uppercase px-2 py-1 select-none z-10">
            Sold Out
          </span>
        ) : isLowStock ? (
          <span className="absolute top-3 left-3 bg-amber-500 text-white text-[9px] font-bold tracking-widest uppercase px-2 py-1 select-none z-10">
            Low Stock
          </span>
        ) : product.featured && !hasDiscount ? (
          <span className="absolute top-3 left-3 bg-zinc-950 text-white text-[9px] font-bold tracking-widest uppercase px-2 py-1 select-none z-10">
            Featured
          </span>
        ) : hasDiscount ? (
          <span className="absolute top-3 left-3 bg-red-600 text-white text-[9px] font-bold tracking-widest uppercase px-2 py-1 select-none z-10">
            Sale
          </span>
        ) : null}

        {/* Flash Sale Timer */}
        {timeLeft && (
          <div className="absolute bottom-3 left-3 right-3 bg-zinc-950/90 backdrop-blur-sm text-white text-[10px] font-bold tracking-wider text-center py-1.5 px-2 select-none z-10 rounded-sm flex items-center justify-center gap-1.5">
            <span className="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse"></span>
            Ends in {timeLeft}
          </div>
        )}

        {/* ── Hover slide-up drawer ── */}
        <div
          className={`absolute bottom-0 left-0 right-0 bg-white/95 backdrop-blur-sm border-t border-zinc-200 p-4 flex flex-col gap-3 z-20 transition-all duration-300 transform ${
            hovered ? "translate-y-0 opacity-100" : "translate-y-full opacity-0"
          }`}
        >
          {/* SIZE row */}
          {uniqueSizes.length > 0 && (
            <div>
              <p className="text-[9px] font-black text-zinc-500 tracking-widest uppercase mb-2">
                SIZE
              </p>
              <div className="flex flex-wrap gap-1.5">
                {uniqueSizes.map((size) => (
                  <button
                    key={size}
                    onClick={() => setSelectedSize(size === selectedSize ? "" : size)}
                    className={`px-2.5 py-1 text-[10px] font-bold uppercase tracking-wider border transition-all cursor-pointer rounded-sm ${
                      selectedSize === size
                        ? "bg-zinc-950 text-white border-zinc-950"
                        : "bg-white text-zinc-600 border-zinc-300 hover:border-zinc-700 hover:text-zinc-950"
                    }`}
                  >
                    {size}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* LENGTH row */}
          {uniqueLengths.length > 0 && (
            <div>
              <p className="text-[9px] font-black text-zinc-500 tracking-widest uppercase mb-2">
                LENGTH
              </p>
              <div className="flex flex-wrap gap-1.5">
                {uniqueLengths.map((len) => (
                  <button
                    key={len}
                    onClick={() => setSelectedLength(len === selectedLength ? "" : len)}
                    className={`px-2.5 py-1 text-[10px] font-bold uppercase tracking-wider border transition-all cursor-pointer rounded-sm ${
                      selectedLength === len
                        ? "bg-zinc-950 text-white border-zinc-950"
                        : "bg-white text-zinc-600 border-zinc-300 hover:border-zinc-700 hover:text-zinc-950"
                    }`}
                  >
                    {len}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Add to Cart CTA */}
          <button
            onClick={handleAddToCart}
            disabled={isOutOfStock}
            className={`w-full py-3 text-[10px] font-black tracking-widest uppercase flex items-center justify-center gap-2 rounded-sm transition-all duration-300 shadow-sm ${
              isOutOfStock 
                ? "bg-zinc-200 text-zinc-400 cursor-not-allowed"
                : added
                  ? "bg-emerald-600 text-white cursor-pointer"
                  : "bg-zinc-950 text-white hover:bg-zinc-800 active:scale-[0.98] cursor-pointer"
            }`}
          >
            {isOutOfStock ? (
              <>Out of Stock</>
            ) : added ? (
              <>
                <Check className="w-3.5 h-3.5" strokeWidth={3} />
                Added to Cart
              </>
            ) : (
              <>
                <ShoppingBag className="w-3.5 h-3.5" />
                Add to Cart
              </>
            )}
          </button>
        </div>
      </div>

      {/* ── Info ── */}
      <div className="py-4 flex flex-col flex-1">
        {(() => {
          const name = typeof storeName !== 'undefined' ? storeName : "Store";
          return (
            <span className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest block mb-1">
              {product.brand?.name || name} / {product.category?.name || "CLOTHING"}
            </span>
          );
        })()}

        {/* Title */}
        <h3 className="text-[13px] font-bold text-zinc-900 tracking-wide uppercase line-clamp-1 mb-1 leading-snug">
          <Link href={`/product/${product.slug}`} className="hover:text-zinc-600 transition-colors">
            {product.title}
          </Link>
        </h3>

        {/* Color label */}
        <span className="text-xs text-zinc-400 font-medium mb-1.5 block select-none">
          {colorLabel}
        </span>

        {/* Pricing */}
        <div className="flex items-center gap-2 mb-1.5 select-none">
          {hasDiscount ? (
            <>
              <span className="text-[13px] font-black text-red-600">
                {formatPrice(discountPrice as number)}
              </span>
              <span className="text-[11px] text-zinc-400 line-through font-light">
                {formatPrice(originalPrice)}
              </span>
            </>
          ) : (
            <span className="text-[13px] font-black text-zinc-900">
              {formatPrice(originalPrice)}
            </span>
          )}
        </div>


      </div>
    </div>
  );
}
