'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { useShopifyCart } from '@/hooks/use-shopify-cart';
import { truncate } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Loader } from '@/app/components/ui/loader';

interface ProductImage {
  url: string;
  altText?: string;
}

interface ProductPrice {
  amount: string;
  currencyCode: string;
}

interface ProductVariant {
  id: string;
  title: string;
  price: ProductPrice;
  availableForSale: boolean;
}

interface Product {
  id: string;
  title: string;
  description?: string;
  handle: string;
  images: {
    edges: Array<{
      node: ProductImage;
    }>;
  };
  priceRange: {
    minVariantPrice: ProductPrice;
  };
  compareAtPriceRange?: {
    minVariantPrice: ProductPrice;
  };
  variants: {
    edges: Array<{
      node: ProductVariant;
    }>;
  };
}

interface ProductCardProps {
  product: Product;
  onAddToCart?: (product: Product) => void;
}

const ProductCard: React.FC<ProductCardProps> = ({ product, onAddToCart }) => {
  const { addItem, openCart } = useShopifyCart();
  const [isAdding, setIsAdding] = useState(false);

  const firstImage = product.images.edges[0]?.node;
  const price = product.priceRange.minVariantPrice;
  const compareAtPrice = product.compareAtPriceRange?.minVariantPrice;
  const hasDiscount =
    compareAtPrice &&
    parseFloat(compareAtPrice.amount) > parseFloat(price.amount);
  const firstVariant = product.variants.edges[0]?.node;
  const isAvailable = firstVariant?.availableForSale || false;

  const formatPrice = (amount: string) => {
    return `$${parseFloat(amount).toFixed(2)}`;
  };

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

    if (!firstVariant || !isAvailable || isAdding) return;

    try {
      setIsAdding(true);
      await addItem(firstVariant.id, 1);
      openCart();
      if (onAddToCart) onAddToCart(product);
    } catch (err) {
      console.error('Failed to add item to cart:', err);
    } finally {
      setIsAdding(false);
    }
  };

  return (
    <div className="card-modern group bg-card rounded-2xl overflow-hidden h-full flex flex-col">
      {/* Product Image */}
      <div className="relative aspect-[4/3.1] bg-zinc-100 overflow-hidden">
        <Link href={`/products/${product.handle}`} className="block h-full">
          {firstImage ? (
            <img
              src={firstImage.url}
              alt={firstImage.altText || product.title}
              className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-[1.08]"
            />
          ) : (
            <div className="absolute inset-0 flex items-center justify-center text-zinc-300">
              <i className="ri-image-line text-8xl"></i>
            </div>
          )}
        </Link>

        {/* Badges */}
        {hasDiscount && compareAtPrice && (
          <Badge className="absolute top-4 left-4 bg-rose-600 hover:bg-rose-600 text-white text-xs font-medium px-3 py-1 shadow-sm">
            SALE
          </Badge>
        )}

        {!isAvailable && (
          <div className="absolute top-4 right-4 bg-white/90 text-xs font-medium px-3 py-1 rounded-full border text-foreground/70">
            SOLD OUT
          </div>
        )}
      </div>

      {/* Product Info */}
      <div className="flex-1 p-6 flex flex-col">
        <Link
          href={`/products/${product.handle}`}
          className="group-hover:text-primary transition-colors"
        >
          <h3 className="font-heading text-xl font-semibold tracking-tight text-foreground mb-2 line-clamp-2 min-h-[3.2em]">
            {truncate(product.title, 65)}
          </h3>
        </Link>

        <div className="mt-auto">
          <div className="price-display flex items-baseline gap-x-3 mb-6">
            <span className="text-2xl font-semibold text-foreground tracking-tighter">
              {formatPrice(price.amount)}
            </span>
            {hasDiscount && compareAtPrice && (
              <span className="text-base line-through text-muted-foreground">
                {formatPrice(compareAtPrice.amount)}
              </span>
            )}
          </div>

          <div className="flex gap-3">
            <Link href={`/products/${product.handle}`} className="flex-1">
              <Button
                variant="outline"
                className="w-full btn-modern text-sm font-medium"
              >
                DETAILS
              </Button>
            </Link>

            {isAvailable && (
              <Button
                onClick={handleAddToCart}
                className="flex-1 btn-modern bg-primary hover:bg-primary/90 text-sm font-medium"
                disabled={isAdding || !isAvailable}
              >
                {isAdding ? (
                  <>
                    <Loader size={16} className="mr-2" />
                    ADDING...
                  </>
                ) : (
                  'ADD TO BAG'
                )}
              </Button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default ProductCard;
