import React, { useState, useEffect } from 'react';
import { Heart, Trash2, ShoppingBag, X, ArrowRight, Check } from 'lucide-react';
import { WCProduct } from '../services/woocommerce';
import {
  getWishlistItems,
  removeFromWishlist,
  clearWishlist,
  subscribeToWishlist,
} from '../services/wishlistService';
import { getEffectiveProductRating } from '../services/reviewService';

interface WishlistModalProps {
  isOpen: boolean;
  onClose: () => void;
  onAddToCart: (product: WCProduct) => void;
  onSelectProduct: (product: WCProduct) => void;
}

export const WishlistModal: React.FC<WishlistModalProps> = ({
  isOpen,
  onClose,
  onAddToCart,
  onSelectProduct,
}) => {
  const [wishlistItems, setWishlistItems] = useState<WCProduct[]>([]);
  const [addedIds, setAddedIds] = useState<number[]>([]);

  useEffect(() => {
    const unsub = subscribeToWishlist((items) => {
      setWishlistItems(items);
    });
    return () => unsub();
  }, []);

  if (!isOpen) return null;

  const handleAddToCart = (e: React.MouseEvent, product: WCProduct) => {
    e.stopPropagation();
    onAddToCart(product);
    setAddedIds((prev) => [...prev, product.id]);
    setTimeout(() => {
      setAddedIds((prev) => prev.filter((id) => id !== product.id));
    }, 2000);
  };

  const handleRemove = (e: React.MouseEvent, productId: number) => {
    e.stopPropagation();
    removeFromWishlist(productId);
  };

  const handleClearAll = () => {
    if (confirm('Are you sure you want to clear your entire wishlist?')) {
      clearWishlist();
    }
  };

  return (
    <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4 animate-in fade-in duration-200 font-sans">
      <div className="bg-white max-w-2xl w-full rounded-3xl shadow-2xl overflow-hidden border border-stone-200 flex flex-col max-h-[85vh]">
        
        {/* Header */}
        <div className="p-5 bg-[#1C1814] text-white flex items-center justify-between border-b border-amber-900/40 shrink-0">
          <div className="flex items-center gap-2.5">
            <div className="w-10 h-10 rounded-2xl bg-[#C81E3D]/20 border border-[#C81E3D]/40 flex items-center justify-center text-[#FF859B]">
              <Heart className="w-5 h-5 fill-[#FF859B]" />
            </div>
            <div>
              <h3 className="text-lg font-serif font-bold text-amber-50">My Saved Wishlist</h3>
              <p className="text-xs text-amber-200/70">
                {wishlistItems.length} {wishlistItems.length === 1 ? 'item' : 'items'} saved in local storage
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            {wishlistItems.length > 0 && (
              <button
                onClick={handleClearAll}
                className="text-xs text-rose-300 hover:text-rose-100 bg-rose-950/60 hover:bg-rose-900 border border-rose-800/60 px-3 py-1.5 rounded-xl font-bold transition-all cursor-pointer flex items-center gap-1"
              >
                <Trash2 className="w-3.5 h-3.5" />
                <span>Clear All</span>
              </button>
            )}

            <button
              onClick={onClose}
              className="p-2 text-stone-400 hover:text-white rounded-xl transition-colors cursor-pointer"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Content Body */}
        <div className="p-6 overflow-y-auto space-y-4 flex-1">
          {wishlistItems.length === 0 ? (
            <div className="py-12 text-center space-y-3">
              <div className="w-16 h-16 bg-rose-50 text-rose-300 border border-rose-200 rounded-full flex items-center justify-center mx-auto">
                <Heart className="w-8 h-8" />
              </div>
              <h4 className="text-base font-bold text-stone-800 font-serif">Your wishlist is empty</h4>
              <p className="text-xs text-stone-500 max-w-md mx-auto">
                Explore our pure Shilajit and organic health products and click the heart icon to save your favorites for later!
              </p>
              <button
                onClick={onClose}
                className="mt-2 inline-flex items-center gap-2 px-5 py-2.5 bg-[#C81E3D] hover:bg-[#A6142E] text-white rounded-xl text-xs font-bold uppercase tracking-wider transition-all cursor-pointer"
              >
                <span>Browse Products</span>
                <ArrowRight className="w-4 h-4" />
              </button>
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {wishlistItems.map((product) => {
                const effectiveRating = getEffectiveProductRating(product);
                const isAdded = addedIds.includes(product.id);
                const price = typeof product.price === 'string' ? parseFloat(product.price) || 0 : product.price;

                return (
                  <div
                    key={product.id}
                    onClick={() => {
                      onSelectProduct(product);
                      onClose();
                    }}
                    className="bg-stone-50 hover:bg-amber-50/40 rounded-2xl p-4 border border-stone-200 flex gap-3 transition-all cursor-pointer group relative"
                  >
                    {/* Image */}
                    <div className="w-20 h-20 bg-white rounded-xl border border-stone-200 overflow-hidden shrink-0 relative">
                      <img
                        src={product.images?.[0]?.src || 'https://timenlife.com/wp-content/uploads/2025/01/TimeNLifeLogo-300x300-1.png'}
                        alt={product.name}
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                      />
                    </div>

                    {/* Details */}
                    <div className="flex-1 flex flex-col justify-between min-w-0">
                      <div>
                        <h4 className="text-xs font-bold text-stone-900 group-hover:text-[#C81E3D] transition-colors truncate">
                          {product.name}
                        </h4>
                        
                        <div className="flex items-center gap-1 text-[11px] text-amber-800 font-bold mt-0.5">
                          <span>Rs {price.toLocaleString('en-PK')}</span>
                          {effectiveRating.ratingCount > 0 && (
                            <span className="text-amber-600 text-[10px]">
                              • ★ {effectiveRating.averageRating} ({effectiveRating.ratingCount})
                            </span>
                          )}
                        </div>
                      </div>

                      {/* Action Buttons */}
                      <div className="flex items-center justify-between gap-2 pt-2">
                        <button
                          onClick={(e) => handleAddToCart(e, product)}
                          className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer ${
                            isAdded
                              ? 'bg-emerald-600 text-white'
                              : 'bg-[#C81E3D] hover:bg-[#A6142E] text-white shadow-xs'
                          }`}
                        >
                          {isAdded ? (
                            <>
                              <Check className="w-3.5 h-3.5" />
                              <span>Added</span>
                            </>
                          ) : (
                            <>
                              <ShoppingBag className="w-3.5 h-3.5" />
                              <span>Add to Cart</span>
                            </>
                          )}
                        </button>

                        <button
                          onClick={(e) => handleRemove(e, product.id)}
                          className="p-1.5 text-stone-400 hover:text-rose-600 hover:bg-rose-50 rounded-lg transition-colors cursor-pointer"
                          title="Remove from Wishlist"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="p-4 bg-stone-100 border-t border-stone-200 flex items-center justify-between shrink-0 text-xs">
          <span className="text-stone-500 text-[11px]">
            Items in wishlist are saved persistently on your device.
          </span>

          <button
            onClick={onClose}
            className="px-4 py-2 bg-stone-800 hover:bg-stone-900 text-amber-50 font-bold rounded-xl cursor-pointer"
          >
            Close
          </button>
        </div>

      </div>
    </div>
  );
};
