"use client";

import { useState } from "react";
import { useCart, Product } from "@/components/CartContext";
import { motion, AnimatePresence } from "framer-motion";
import { Package, ShoppingBag } from "lucide-react";
import {
  isMerchCategoryVisible,
  normalizeMerchCategory,
  type MerchGroupVisibility,
} from "@/lib/merch-config";
import { normalizeMediaUrl } from "@/lib/media-url";

type Props = {
  products: Product[];
  enabled: boolean;
  groupVisibility: MerchGroupVisibility;
};

export default function MerchStoreFront({ products, enabled, groupVisibility }: Props) {
  const { addToCart } = useCart();
  const [activeCategory, setActiveCategory] = useState<string>("TODOS");

  if (!enabled) {
    return null;
  }

  const physicalProducts = products.filter(
    (p) =>
      p.type === "PHYSICAL" &&
      p.stock > 0 &&
      isMerchCategoryVisible(p.category, groupVisibility)
  );

  if (physicalProducts.length === 0) {
    return null;
  }

  const visibleCategories = Array.from(
    new Set(physicalProducts.map((p) => normalizeMerchCategory(p.category)))
  ).sort((a, b) => a.localeCompare(b, "es"));

  const categories = ["TODOS", ...visibleCategories];

  const filteredProducts =
    activeCategory === "TODOS"
      ? physicalProducts
      : physicalProducts.filter(
          (p) => normalizeMerchCategory(p.category) === activeCategory
        );

  return (
    <section id="merch" className="py-12 sm:py-16 relative">
      <div className="text-center mb-10 max-w-xl mx-auto space-y-3">
        <span className="text-xs font-bold uppercase tracking-[0.2em] text-brand-purple">
          Tienda solidaria
        </span>
        <h2 className="text-2xl font-extrabold text-brand-ink md:text-3xl">
          Productos que <span className="text-gradient">también ayudan</span>
        </h2>
        <p className="text-brand-muted text-sm sm:text-base">
          Cada compra en la tienda también apoya los programas de la fundación.
        </p>
      </div>

      {categories.length > 2 && (
        <div className="flex flex-wrap justify-center gap-2 mb-10 px-4">
          {categories.map((category) => (
            <button
              key={category}
              onClick={() => setActiveCategory(category)}
              className={`px-4 py-2 rounded-xl text-sm font-semibold transition-all relative ${
                activeCategory === category
                  ? "text-white z-10"
                  : "text-brand-muted hover:text-brand-ink bg-white border border-slate-200 hover:border-brand-purple/40"
              }`}
            >
              {activeCategory === category && (
                <motion.div
                  layoutId="activeCategoryBg"
                  className="absolute inset-0 bg-brand-purple rounded-xl -z-10 shadow-md"
                  transition={{ type: "spring", stiffness: 380, damping: 30 }}
                />
              )}
              {category === "TODOS"
                ? "Todos"
                : category.charAt(0).toUpperCase() + category.slice(1).toLowerCase()}
            </button>
          ))}
        </div>
      )}

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 px-4 max-w-7xl mx-auto">
        <AnimatePresence mode="popLayout">
          {filteredProducts.map((product) => {
            const isOutOfStock = product.stock <= 0;
            const isLowStock = product.stock > 0 && product.stock <= 5;
            const imgSrc = normalizeMediaUrl(product.image);

            return (
              <motion.div
                key={product.id}
                layout
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.9 }}
                whileHover={{ y: -6 }}
                transition={{ duration: 0.25 }}
                className="card-soft p-5 flex flex-col justify-between group relative overflow-hidden"
              >
                
                <div className="h-48 w-full rounded-lg overflow-hidden bg-brand-soft mb-4 flex items-center justify-center relative border border-slate-200">
                  {imgSrc ? (
                    <img
                      src={imgSrc}
                      alt={product.name}
                      className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
                    />
                  ) : (
                    <Package className="w-12 h-12 text-slate-300" />
                  )}

                  {isOutOfStock ? (
                    <div className="absolute top-2 right-2 bg-red-600 text-white text-[10px] uppercase font-bold px-2 py-0.5 rounded-md shadow-sm">
                      Agotado
                    </div>
                  ) : isLowStock ? (
                    <div className="absolute top-2 right-2 bg-brand-pink text-white text-[10px] uppercase font-bold px-2 py-0.5 rounded-md shadow-sm animate-pulse">
                      ¡Últimos {product.stock}!
                    </div>
                  ) : null}
                </div>

                <div className="flex-1 flex flex-col justify-between space-y-3">
                  <div>
                    <span className="text-[10px] uppercase font-semibold text-brand-cyan tracking-wider">
                      {normalizeMerchCategory(product.category)}
                    </span>
                    <h3 className="font-serif text-lg font-bold text-brand-ink group-hover:text-brand-purple transition-colors line-clamp-1">
                      {product.name}
                    </h3>
                    <p className="text-brand-muted text-xs line-clamp-2 mt-1 min-h-[32px]">
                      {product.description}
                    </p>
                  </div>

                  <div className="flex items-center justify-between pt-2 border-t border-slate-200">
                    <span className="font-serif text-xl font-bold text-brand-ink">
                      ${product.price.toLocaleString("es-CL")}
                    </span>

                    <button
                      onClick={() => addToCart(product)}
                      disabled={isOutOfStock}
                      className={`flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-bold transition-all z-10 ${
                        isOutOfStock
                          ? "bg-slate-100 text-slate-400 cursor-not-allowed"
                          : "bg-brand-gradient text-white hover:opacity-90"
                      }`}
                    >
                      <ShoppingBag className="w-3.5 h-3.5" />
                      Agregar
                    </button>
                  </div>
                </div>
              </motion.div>
            );
          })}
        </AnimatePresence>
      </div>
    </section>
  );
}
