"use client";
import React, { memo, useState, useCallback } from "react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import Image from "next/image";
import Link from "next/link";
import { ShoppingCart, Package, Tag } from "lucide-react";
import { useCart } from "@/context/CartContext";
import { useToast } from "@/context/ToastContext";
import type { PackageDeal } from "@/types/package";

interface PackageCardProps {
  packageDeal: PackageDeal;
  className?: string;
}

const PackageCard: React.FC<PackageCardProps> = memo(({ packageDeal, className = "" }) => {
  const { addToCart } = useCart();
  const { showToast } = useToast();
  const [isAddingToCart, setIsAddingToCart] = useState(false);
  const [justAdded, setJustAdded] = useState(false);
  const [imageError, setImageError] = useState(false);

  const mainImage = packageDeal.images?.[0] || packageDeal.products?.[0]?.images?.[0] || '/assets/placeholder.png';
  const productCount = packageDeal.products?.length || 0;
  const savings = packageDeal.original_price - packageDeal.package_price;

  const handleAddToCart = useCallback(async () => {
    if (isAddingToCart || !packageDeal.available) return;

    setIsAddingToCart(true);
    
    try {
      // Add all products from the package to cart
      if (packageDeal.products && packageDeal.products.length > 0) {
        for (const product of packageDeal.products) {
          const cartProduct = {
            id: product.id.toString(),
            title: product.name,
            price: product.base_price,
            imageSrc: product.images && product.images.length > 0 ? product.images[0] : mainImage,
            slug: product.slug || '',
          };
          
          await addToCart(cartProduct, product.pivot?.quantity || 1);
        }
        
        setJustAdded(true);
        setTimeout(() => setJustAdded(false), 1000);
        
        showToast({
          type: 'success',
          title: 'Package Added',
          description: `${packageDeal.name} added to cart`,
          duration: 2000,
        });
      }
    } catch (err) {
      console.error('Cart error:', err);
      showToast({
        type: 'error',
        title: 'Error',
        description: 'Failed to add package to cart',
        duration: 3000,
      });
    } finally {
      setIsAddingToCart(false);
    }
  }, [packageDeal, isAddingToCart, mainImage, addToCart, showToast]);

  const handleImageError = useCallback(() => setImageError(true), []);

  return (
    <Card className={`w-full shadow-lg border-2 border-orange-200 hover:border-orange-400 transition-all hover:scale-[1.02] ${className}`}>
      <div className="relative group">
        {/* Discount Badge */}
        <div className="absolute left-3 top-3 z-20">
          <Badge className="bg-red-500 text-white px-3 py-1.5 text-base font-bold shadow-lg">
            <Tag className="w-4 h-4 mr-1" />
            {packageDeal.discount_percentage}% OFF
          </Badge>
        </div>

        {/* Package Badge */}
        <div className="absolute right-3 top-3 z-20">
          <Badge className="bg-orange-500 text-white px-3 py-1.5 text-sm font-bold shadow-lg">
            <Package className="w-4 h-4 mr-1" />
            {productCount} Items
          </Badge>
        </div>

        {/* Stock Badge */}
        {packageDeal.stock > 0 && packageDeal.stock <= 5 && (
          <div className="absolute left-3 top-14 z-20">
            <Badge variant="yellow" className="text-xs font-semibold">
              Only {packageDeal.stock} left!
            </Badge>
          </div>
        )}

        {/* Main Image */}
        <div className="bg-gradient-to-br from-orange-50 to-orange-100 rounded-t-lg h-[280px] relative overflow-hidden">
          <Link href={`/packages/${packageDeal.slug}`} className="block h-full">
            {!imageError ? (
              mainImage.startsWith('data:image') ? (
                <img 
                  src={mainImage} 
                  alt={packageDeal.name} 
                  className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-300"
                  loading="lazy"
                  onError={handleImageError}
                />
              ) : (
                <Image 
                  src={mainImage} 
                  alt={packageDeal.name} 
                  fill 
                  className="object-cover group-hover:scale-110 transition-transform duration-300"
                  loading="lazy"
                  sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 33vw"
                  onError={handleImageError}
                  quality={75}
                />
              )
            ) : (
              <div className="w-full h-full bg-gray-200 flex items-center justify-center">
                <Package className="w-16 h-16 text-gray-400" />
              </div>
            )}
          </Link>
        </div>

        {/* Product Thumbnails */}
        {packageDeal.products && packageDeal.products.length > 0 && (
          <div className="absolute bottom-3 left-3 right-3 flex gap-2 overflow-x-auto pb-1 scrollbar-hide">
            {packageDeal.products.slice(0, 4).map((product) => (
              <div
                key={product.id}
                className="flex-shrink-0 w-12 h-12 bg-white rounded border-2 border-white shadow-md overflow-hidden"
              >
                <Image
                  src={product.images?.[0] || '/assets/placeholder.png'}
                  alt={product.name}
                  width={48}
                  height={48}
                  className="w-full h-full object-cover"
                />
              </div>
            ))}
            {packageDeal.products.length > 4 && (
              <div className="flex-shrink-0 w-12 h-12 bg-gray-800 bg-opacity-75 rounded border-2 border-white shadow-md flex items-center justify-center text-white text-xs font-bold">
                +{packageDeal.products.length - 4}
              </div>
            )}
          </div>
        )}
      </div>

      {/* Content */}
      <div className="p-4 space-y-3 bg-white rounded-b-lg">
        {/* Title */}
        <Link href={`/packages/${packageDeal.slug}`}>
          <h3 className="font-bold text-lg text-gray-900 hover:text-orange-600 transition-colors line-clamp-2 min-h-[56px]">
            {packageDeal.name}
          </h3>
        </Link>

        {/* Description */}
        {packageDeal.description && (
          <p className="text-gray-600 text-sm line-clamp-2">
            {packageDeal.description}
          </p>
        )}

        {/* Pricing */}
        <div className="space-y-1">
          <div className="flex items-baseline justify-between gap-2">
            <div>
              <span className="text-2xl font-bold text-orange-600">
                {packageDeal.package_price.toLocaleString()} د.ع
              </span>
            </div>
            <div className="text-right">
              <div className="text-sm text-gray-500 line-through">
                {packageDeal.original_price.toLocaleString()} د.ع
              </div>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <Badge variant="lime" className="text-xs">
              Save {savings.toLocaleString()} د.ع
            </Badge>
            <span className="text-xs text-gray-500">
              ({packageDeal.discount_percentage}% discount)
            </span>
          </div>
        </div>

        {/* Add to cart button */}
        <Button 
          variant="outline" 
          onClick={handleAddToCart}
          disabled={isAddingToCart || justAdded || !packageDeal.available || packageDeal.stock === 0}
          className={`w-full rounded-full border-orange-500 text-orange-600 hover:bg-orange-500 hover:text-white transition-all duration-300 ${
            justAdded ? 'bg-green-500 border-green-500 text-white scale-105' : ''
          } ${
            isAddingToCart ? 'scale-95' : 'hover:scale-105'
          }`}
        >
          {justAdded ? (
            <>
              <svg 
                className="w-5 h-5 mr-2 animate-bounce" 
                fill="none" 
                stroke="currentColor" 
                viewBox="0 0 24 24"
              >
                <path 
                  strokeLinecap="round" 
                  strokeLinejoin="round" 
                  strokeWidth={2} 
                  d="M5 13l4 4L19 7" 
                />
              </svg>
              Added!
            </>
          ) : (
            <>
              <ShoppingCart className={`w-4 h-4 mr-2 transition-transform duration-300 ${
                isAddingToCart ? 'animate-pulse' : ''
              }`} />
              {packageDeal.stock === 0 ? 'Out of Stock' : isAddingToCart ? "Adding..." : "Add Package"}
            </>
          )}
        </Button>
      </div>
    </Card>
  );
});

PackageCard.displayName = 'PackageCard';

export default PackageCard;
