"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { generateSlug } from "../../utils/slugHelper";
import { resolveImage, PLACEHOLDER_IMAGE } from "../../utils/imageHelper";
import { useCart } from "../context/CartContext";
import { useRouter } from "next/navigation";
import { formatPrice } from "../../utils/currencyHelper";

type Product = {
  inward_id: string;
  variant_id: string;
  sku_no: string;
  name: string;
  image: string | null;
  dealer_price: number;
  mrp: number;
  currency?: string;
  color?: string | null;
  size_name?: string | null;
  is_individual: boolean;
  is_carton: boolean;
  is_featured: boolean;
  is_new_arrival: boolean;
  is_best_seller: boolean;
  is_active: boolean;
  category_id: string | null;
  category_name: string | null;
  subcategory_id: string | null;
  subcategory_name?: string | null;
  carton_box_size?: number;
  total_variants?: number;
};

export default function SubcategoryProductCard({ 
  product, 
  parentSlug, 
  subcatSlug,
  subcatName
}: { 
  product: Product;
  parentSlug: string;
  subcatSlug: string;
  subcatName: string;
}) {
  const [quantity, setQuantity] = useState(
    product.is_carton ? (product.carton_box_size || 1) : 1
  );
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [mounted, setMounted] = useState(false);
  const [adding, setAdding] = useState(false);
  const { openCart } = useCart();
  const router = useRouter();

  const boxSize = product.carton_box_size || 1;
  const isCarton = product.is_carton;
  const productSlug = generateSlug(product.name);
  const productLink = `/category/${parentSlug}/${subcatSlug}/${productSlug}`;

  useEffect(() => {
    setMounted(true);
    const checkAuth = () => setIsLoggedIn(!!localStorage.getItem("access_token"));
    checkAuth();
    window.addEventListener('storage', checkAuth);
    return () => window.removeEventListener('storage', checkAuth);
  }, []);

  const handleActionClick = (e: React.MouseEvent) => {
    e.stopPropagation();
  };

  const increment = () => setQuantity((p) => p + (isCarton ? boxSize : 1));
  const decrement = () => setQuantity((p) => Math.max(isCarton ? boxSize : 1, p - (isCarton ? boxSize : 1)));

  const handleInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    if (value === "") {
      setQuantity(0);
    } else {
      const num = parseInt(value, 10);
      if (!isNaN(num) && num >= 0) {
        if (isCarton) {
          const roundedQuantity = Math.ceil(num / boxSize) * boxSize;
          setQuantity(roundedQuantity);
        } else {
          setQuantity(num);
        }
      }
    }
  };

  const handleAddToCart = async (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (quantity < 1) return;
    const token = localStorage.getItem("access_token");
    if (!token) { router.push('/login'); return; }

    setAdding(true);
    try {
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/b2b-cart/items`, {
        method: "POST",
        headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
        body: JSON.stringify({ inward_id: product.inward_id, quantity }),
      });
      if (res.ok) openCart();
      else {
        const err = await res.json().catch(() => ({}));
        alert(`Failed to add: ${err.detail || "Unknown error"}`);
      }
    } catch {
      alert("Failed to add item to cart.");
    } finally {
      setAdding(false);
    }
  };

  return (
    <Link
      href={productLink}
      className="group relative overflow-hidden rounded-[2rem] bg-gray-900 shadow-lg hover:shadow-[0_20px_50px_rgba(0,0,0,0.15)] transition-all duration-500 transform hover:-translate-y-2 aspect-[4/3] w-full block border border-white/5"
    >
      {/* Background Product Image */}
      <div
        className="absolute inset-0 bg-cover bg-center transition-transform duration-750 group-hover:scale-103"
        style={{ backgroundImage: `url('${resolveImage(product.image) || PLACEHOLDER_IMAGE}')` }}
      />
      
      {/* Linear dark gradient overlay */}
      <div className="absolute inset-0 bg-gradient-to-t from-black/95 via-black/45 to-transparent transition-opacity duration-300 group-hover:from-black/98" />

      {/* Top Badges */}
      <div className="absolute top-4 right-4 flex justify-end items-center z-10">
        <span className="bg-[#FF9F43] text-white text-[9px] font-black uppercase tracking-widest px-2.5 py-1 rounded-lg shadow-sm">
          {product.color || "View Details"}
        </span>
      </div>

      {/* Text Overlay & CTA */}
      <div className="absolute bottom-0 left-0 p-5 sm:p-6 w-full flex flex-col justify-end min-h-[55%] z-10">
        <div className="flex items-center justify-between mb-1">
          <span className="text-[9px] font-black text-[#FFC633] uppercase tracking-widest">
            {subcatName}
          </span>
          {product.total_variants !== undefined && (
            <span className="text-[9px] font-black text-white/85 uppercase tracking-widest bg-white/10 px-2 py-0.5 rounded">
              {product.total_variants} {product.total_variants === 1 ? "Variant" : "Variants"}
            </span>
          )}
        </div>
        <h3 className="text-lg sm:text-xl font-black text-white mb-1.5 leading-tight line-clamp-1">
          {product.name}
        </h3>
        <p className="text-white/70 font-semibold text-[11px] leading-relaxed mb-4 line-clamp-2 max-w-md">
          Premium B2B helmet with impact resistant shell, dynamic ventilation systems, and certified security protection.
        </p>

        {/* Actions removed */}
      </div>
    </Link>
  );
}
