"use client";

import Link from "next/link";
import { useState } from "react";
import { motion } from "framer-motion";
import { Star, ShoppingBag } from "lucide-react";
import { toast } from "sonner";
import type { Product } from "@/data/products";
import { useCart } from "@/context/CartContext";

const ProductCard = ({ product, index = 0 }: { product: Product; index?: number }) => {
  const [selectedColor, setSelectedColor] = useState(0);
  const [isHovered, setIsHovered] = useState(false);
  const { addToCart } = useCart();
  const discount = product.originalPrice
    ? Math.round(((product.originalPrice - product.price) / product.originalPrice) * 100)
    : 0;

  const handleQuickAdd = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    addToCart(product, product.colors[selectedColor].name);
    toast.success(`${product.name} added to cart`);
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 30, scale: 0.98 }}
      whileInView={{ opacity: 1, y: 0, scale: 1 }}
      viewport={{ once: true, amount: 0.2 }}
      transition={{ duration: 0.5, delay: index * 0.07, ease: [0.22, 1, 0.36, 1] }}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      <Link href={`/product/${product.id}`} className="group block">
        <div className="relative overflow-hidden rounded-2xl border border-border/40 bg-card shadow-card transition-all duration-500 hover:border-border hover:shadow-card-hover">
          <div className="absolute left-3 top-3 z-10 flex flex-col gap-1.5">
            {product.badge && (
              <span className="rounded-lg bg-accent px-2.5 py-1 text-[10px] font-bold uppercase tracking-wider text-primary-foreground shadow-md">
                {product.badge}
              </span>
            )}
            {discount > 0 && (
              <span className="rounded-lg bg-destructive px-2.5 py-1 text-[10px] font-bold text-primary-foreground">
                -{discount}%
              </span>
            )}
          </div>

          {product.energyRating && (
            <div className="absolute right-3 top-3 z-10 rounded-lg border border-border/40 bg-card/90 px-2 py-1 backdrop-blur-sm">
              <span className="text-[10px] font-bold text-success">⚡ {product.energyRating}</span>
            </div>
          )}

          <div className="aspect-square overflow-hidden p-4">
            {product.colors[selectedColor]?.image ? (
              <img
                src={product.colors[selectedColor].image}
                alt={product.name}
                className="h-full w-full rounded-xl object-cover transition-transform duration-700 group-hover:scale-105"
                loading="lazy"
              />
            ) : (
              <div className="flex h-full w-full items-center justify-center rounded-xl bg-muted text-sm text-muted-foreground">
                No image
              </div>
            )}
          </div>

          <motion.div
            initial={false}
            animate={{ opacity: isHovered ? 1 : 0, y: isHovered ? 0 : 8 }}
            transition={{ duration: 0.2 }}
            className={`absolute bottom-4 left-4 right-4 flex gap-2 ${isHovered ? "pointer-events-auto" : "pointer-events-none"}`}
            onClick={(e) => e.preventDefault()}
          >
            <button
              onClick={handleQuickAdd}
              className="flex flex-1 items-center justify-center gap-2 rounded-xl bg-primary py-2.5 text-xs font-semibold text-primary-foreground shadow-elevated transition-all hover:opacity-90"
            >
              <ShoppingBag className="h-3.5 w-3.5" />
              Quick Add
            </button>
          </motion.div>
        </div>

        <div className="mt-4 space-y-2 px-1">
          <div className="flex items-center justify-between">
            <p className="text-[11px] font-semibold uppercase tracking-[0.15em] text-accent">{product.brand}</p>
            <div className="flex items-center gap-1">
              <Star className="h-3 w-3 fill-accent text-accent" />
              <span className="text-xs font-semibold">{product.rating}</span>
              <span className="text-[10px] text-muted-foreground">({product.reviews.toLocaleString()})</span>
            </div>
          </div>

          <h3 className="text-[15px] font-semibold leading-snug">{product.name}</h3>
          <p className="line-clamp-2 text-xs leading-relaxed text-muted-foreground">{product.description}</p>

          <div className="flex items-center justify-between pt-1">
            <div className="flex items-baseline gap-2">
              <span className="text-xl font-bold">${product.price}</span>
              {product.originalPrice && (
                <span className="text-sm text-muted-foreground line-through">${product.originalPrice}</span>
              )}
            </div>

            <div className="flex items-center gap-1" onClick={(e) => e.preventDefault()}>
              {product.colors.map((color, i) => (
                <button
                  key={color.name}
                  onClick={(e) => {
                    e.preventDefault();
                    setSelectedColor(i);
                  }}
                  className={`h-4 w-4 rounded-full border-[1.5px] transition-all ${
                    selectedColor === i
                      ? "scale-125 border-foreground shadow-sm"
                      : "border-border hover:scale-110"
                  }`}
                  style={{ backgroundColor: color.hex }}
                  title={color.name}
                />
              ))}
            </div>
          </div>
        </div>
      </Link>
    </motion.div>
  );
};

export default ProductCard;
