'use client';

import React from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import {
  Heart,
  ShoppingCart,
  Download,
  Eye,
  CheckCircle2,
  Star,
  Sparkles,
} from 'lucide-react';
import { Product } from '@/types';
import { useWishlist } from '@/context/WishlistContext';
import { useCart } from '@/context/CartContext';
import { useAuth } from '@/context/AuthContext';
import AuthRequiredModal from '@/components/common/AuthRequiredModal';

export default function ProductCard({ product }: { product: Product }) {
  const router = useRouter();
  const { user } = useAuth();
  const { isInWishlist, toggleWishlist } = useWishlist();
  const { addToCart, isInCart } = useCart();
  const [isAuthModalOpen, setIsAuthModalOpen] = React.useState(false);

  const isFavorite = isInWishlist(product.id);
  const inCart = isInCart(product.id);

  const handleAddToCart = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (!user) {
      setIsAuthModalOpen(true);
      return;
    }
    if (product.is_free) {
      router.push(`/order-success/free-${product.id}?free=1`);
    } else {
      addToCart(product);
    }
  };

  const handleWishlistToggle = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    toggleWishlist(product);
  };

  const handlePreviewClick = (e: React.MouseEvent) => {
    e.stopPropagation();
  };

  return (
    <div
      onClick={() => router.push(`/product/${product.id}`)}
      className="group bg-white rounded-2xl shadow-sm hover:shadow-xl border border-gray-100/80 overflow-hidden flex flex-col transition-all duration-300 transform hover:-translate-y-1 cursor-pointer relative"
    >
      {/* Top Media & Badges */}
      <div className="relative aspect-[16/10] overflow-hidden bg-gray-100">
        <img
          src={product.cover_image}
          alt={product.title}
          className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500 ease-out"
          loading="lazy"
        />

        {/* Wishlist Floating Button */}
        <button
          onClick={handleWishlistToggle}
          className="absolute top-3 right-3 w-8 h-8 rounded-full bg-white/90 backdrop-blur shadow-sm hover:bg-white flex items-center justify-center text-gray-500 hover:text-red-500 transition-colors z-10"
          aria-label="Toggle Wishlist"
        >
          <Heart
            className={`w-4 h-4 transition-colors ${
              isFavorite ? 'fill-red-500 text-red-500' : 'text-gray-600'
            }`}
          />
        </button>

        {/* Pricing / Trial Badges */}
        <div className="absolute top-3 left-3 flex items-center gap-1.5 z-10">
          {product.is_free ? (
            <span className="px-2.5 py-0.5 rounded-full text-xs font-bold bg-emerald-500 text-white shadow-sm">
              Free
            </span>
          ) : product.has_trial ? (
            <span className="px-2.5 py-0.5 rounded-full text-xs font-bold bg-blue-600 text-white shadow-sm">
              Trial
            </span>
          ) : product.regular_price && product.regular_price > product.price ? (
            <span className="px-2.5 py-0.5 rounded-full text-xs font-bold bg-amber-500 text-white shadow-sm">
              Sale
            </span>
          ) : (
            <span className="px-2.5 py-0.5 rounded-full text-xs font-bold bg-indigo-600 text-white shadow-sm">
              Premium
            </span>
          )}
        </div>
      </div>

      {/* Content Body */}
      <div className="p-4 sm:p-5 flex-1 flex flex-col justify-between">
        <div>
          {/* Verified & Reviews Line */}
          <div className="flex items-center justify-between mb-2">
            <div className="flex items-center gap-1 text-emerald-600 font-semibold text-xs">
              <CheckCircle2 className="w-3.5 h-3.5 fill-emerald-100" />
              <span>Verified</span>
            </div>

            {/* Stars */}
            <div className="flex items-center gap-1">
              <div className="flex text-amber-400">
                {[...Array(5)].map((_, i) => (
                  <Star
                    key={i}
                    className={`w-3.5 h-3.5 ${
                      i < Math.floor(product.rating || 5)
                        ? 'fill-amber-400 text-amber-400'
                        : 'text-gray-200'
                    }`}
                  />
                ))}
              </div>
              <span className="text-[11px] text-gray-400 font-medium">
                ({product.review_count || 0})
              </span>
            </div>
          </div>

          {/* Title */}
          <h3 className="font-bold text-gray-900 text-base group-hover:text-indigo-600 transition-colors line-clamp-1 mb-1">
            {product.title}
          </h3>

          {/* Category */}
          <p className="text-xs text-gray-500 mb-3">
            Category:{' '}
            <span className="text-indigo-600 font-medium hover:underline">
              {product.category_name}
            </span>
          </p>

          {/* Tech Stack Pills */}
          <div className="flex flex-wrap gap-1.5 mb-4 max-h-7 overflow-hidden">
            {product.tech_stacks.map((tech) => (
              <span
                key={tech}
                className="text-[11px] font-medium bg-indigo-50/80 text-indigo-700 px-2 py-0.5 rounded-md"
              >
                {tech}
              </span>
            ))}
          </div>
        </div>

        {/* Price & Action Row */}
        <div className="pt-3 border-t border-gray-100 flex items-center justify-between mt-auto">
          {/* Price */}
          <div className="flex items-baseline gap-2">
            {product.is_free ? (
              <span className="text-lg font-black text-emerald-600">Free</span>
            ) : (
              <>
                <span className="text-lg font-black text-indigo-600">
                  ${product.price.toFixed(2)}
                </span>
                {product.regular_price && (
                  <span className="text-xs text-gray-400 line-through">
                    ${product.regular_price.toFixed(2)}
                  </span>
                )}
              </>
            )}
          </div>

          {/* Actions */}
          <div className="flex items-center gap-2">
            {product.is_free ? (
              <button
                onClick={handleAddToCart}
                className="w-8 h-8 rounded-full bg-emerald-100 hover:bg-emerald-200 text-emerald-700 flex items-center justify-center transition active:scale-90"
                title="Free Download"
              >
                <Download className="w-4 h-4" />
              </button>
            ) : (
              <button
                onClick={handleAddToCart}
                className={`w-8 h-8 rounded-full flex items-center justify-center transition active:scale-90 shadow-sm ${
                  inCart
                    ? 'bg-emerald-600 text-white'
                    : 'bg-indigo-600 hover:bg-indigo-700 text-white'
                }`}
                title={inCart ? 'In Cart' : 'Add to Cart'}
              >
                <ShoppingCart className="w-4 h-4" />
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Auth Modal */}
      <AuthRequiredModal
        isOpen={isAuthModalOpen}
        onClose={() => setIsAuthModalOpen(false)}
        productTitle={product.title}
        price={product.price}
        redirectUrl={`/product/${product.id}`}
        onSuccess={() => {
          addToCart(product);
          router.push('/cart');
        }}
      />
    </div>
  );
}
