import React from "react";
import { Link } from "react-router-dom";
import { ShoppingCart, Eye } from "lucide-react";
import { Button } from "../ui/button";
import { Badge } from "../ui/badge";
import { useCart } from "../../context/CartContext";
import { useAuth } from "../../context/AuthContext";
import { toast } from "sonner";

const ProductCard = ({ product, viewMode = "grid" }) => {
  const { addToCart } = useCart();
  const { isAuthenticated } = useAuth();

  const handleAddToCart = async (e) => {
    e.preventDefault();
    e.stopPropagation();

    if (!isAuthenticated) {
      toast.error("Please login to add items to cart");
      return;
    }

    try {
      await addToCart(product.id);
      toast.success(`${product.name} added to cart`);
    } catch (error) {
      toast.error("Failed to add item to cart");
    }
  };

  // Get the primary image URL
  const getImageUrl = () => {
    if (product.images && product.images.length > 0) {
      const primaryImage =
        product.images.find((img) => img.is_primary) || product.images[0];
      const url = primaryImage.url || primaryImage.image_url || primaryImage;
      return url.startsWith("/uploads")
        ? `${process.env.REACT_APP_BACKEND_URL}${url}`
        : url;
    }
    return product.image_url;
  };

  // List View Layout
  if (viewMode === "list") {
    return (
      <Link
        to={`/products/${product.id}`}
        className="group flex gap-4 overflow-hidden rounded-xl border border-border/50 bg-card hover:border-primary/50 transition-all duration-300 hover-lift card-hover-border p-4"
        data-testid={`product-card-${product.id}`}
      >
        {/* Image Container - Fixed Size */}
        <div className="relative w-32 h-32 flex-shrink-0 overflow-hidden bg-muted rounded-lg">
          <img
            src={getImageUrl()}
            alt={product.name}
            className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
            loading="lazy"
          />
          {/* Stock Badge */}
          {product.stock <= 5 && product.stock > 0 && (
            <Badge className="absolute top-2 left-2 bg-orange-500 hover:bg-orange-600 text-xs">
              {product.stock} left
            </Badge>
          )}
          {product.stock === 0 && (
            <Badge variant="destructive" className="absolute top-2 left-2 text-xs">
              Out of Stock
            </Badge>
          )}
        </div>

        {/* Content - Flex Container */}
        <div className="flex-1 flex flex-col justify-between min-w-0">
          <div className="space-y-2">
            {/* Category & Brand */}
            <div className="flex items-center gap-2">
              <Badge variant="secondary" className="text-xs capitalize">
                {product.category}
              </Badge>
              {product.brand && (
                <span className="text-xs text-muted-foreground">
                  {product.brand}
                </span>
              )}
            </div>

            {/* Title */}
            <h3 className="font-semibold text-base leading-tight line-clamp-1 group-hover:text-primary transition-colors font-['Outfit']">
              {product.name}
            </h3>
            
            {/* Description if available */}
            {product.description && (
              <p className="text-sm text-muted-foreground line-clamp-2">
                {product.description}
              </p>
            )}
          </div>

          {/* Price & Actions */}
          <div className="flex items-center justify-between pt-2">
            <span className="text-xl font-bold font-['Outfit']">
              ${product.price.toFixed(2)}
            </span>
            <div className="flex items-center gap-2">
              <Button
                size="sm"
                variant="outline"
                className="rounded-full"
                data-testid={`view-product-${product.id}`}
              >
                <Eye className="h-4 w-4 mr-1" />
                View
              </Button>
              <Button
                size="sm"
                className="rounded-full px-4 btn-press"
                onClick={handleAddToCart}
                disabled={product.stock === 0}
                data-testid={`add-to-cart-${product.id}`}
              >
                <ShoppingCart className="h-4 w-4 mr-1" />
                Add to Cart
              </Button>
            </div>
          </div>
        </div>
      </Link>
    );
  }

  // Grid View Layout (Default)
  return (
    <Link
      to={`/products/${product.id}`}
      className="group relative overflow-hidden rounded-xl border border-border/50 bg-card hover:border-primary/50 transition-all duration-300 hover-lift card-hover-border"
      data-testid={`product-card-${product.id}`}
    >
      {/* Image Container */}
      <div className="relative aspect-square overflow-hidden bg-muted">
        <img
          src={getImageUrl()}
          alt={product.name}
          className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
          loading="lazy"
        />

        {/* Overlay Actions */}
        <div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors duration-300 flex items-center justify-center gap-2 opacity-0 group-hover:opacity-100">
          <Button
            size="icon"
            variant="secondary"
            className="rounded-full w-10 h-10 bg-background/90 backdrop-blur-sm hover:bg-background"
            onClick={handleAddToCart}
            data-testid={`add-to-cart-${product.id}`}
          >
            <ShoppingCart className="h-4 w-4" />
          </Button>
          <Button
            size="icon"
            variant="secondary"
            className="rounded-full w-10 h-10 bg-background/90 backdrop-blur-sm hover:bg-background"
            data-testid={`view-product-${product.id}`}
          >
            <Eye className="h-4 w-4" />
          </Button>
        </div>

        {/* Stock Badge */}
        {product.stock <= 5 && product.stock > 0 && (
          <Badge className="absolute top-3 left-3 bg-orange-500 hover:bg-orange-600">
            Only {product.stock} left
          </Badge>
        )}
        {product.stock === 0 && (
          <Badge variant="destructive" className="absolute top-3 left-3">
            Out of Stock
          </Badge>
        )}
      </div>

      {/* Content */}
      <div className="p-4 space-y-2">
        {/* Category & Brand */}
        <div className="flex items-center gap-2">
          <Badge variant="secondary" className="text-xs capitalize">
            {product.category}
          </Badge>
          {product.brand && (
            <span className="text-xs text-muted-foreground">
              {product.brand}
            </span>
          )}
        </div>

        {/* Title */}
        <h3 className="font-semibold text-base leading-tight line-clamp-2 group-hover:text-primary transition-colors font-['Outfit']">
          {product.name}
        </h3>

        {/* Price */}
        <div className="flex items-center justify-between pt-2">
          <span className="text-lg font-bold font-['Outfit']">
            ${product.price.toFixed(2)}
          </span>
          <Button
            size="sm"
            className="rounded-full px-4 btn-press"
            onClick={handleAddToCart}
            disabled={product.stock === 0}
          >
            Add to Cart
          </Button>
        </div>
      </div>
    </Link>
  );
};

export default React.memo(ProductCard);
