import React, { useState, useEffect } from 'react';
import { History, Trash2, ShoppingBag, ArrowRight } from 'lucide-react';
import { WCProduct } from '../services/woocommerce';
import {
  getRecentlyViewed,
  clearRecentlyViewed,
  subscribeToRecentlyViewed,
} from '../services/recentlyViewedService';
import { getEffectiveProductRating } from '../services/reviewService';

interface RecentlyViewedSectionProps {
  onSelectProduct: (product: WCProduct) => void;
  onAddToCart: (product: WCProduct) => void;
  currentProductId?: number;
}

export const RecentlyViewedSection: React.FC<RecentlyViewedSectionProps> = ({
  onSelectProduct,
  onAddToCart,
  currentProductId,
}) => {
  const [recentProducts, setRecentProducts] = useState<WCProduct[]>([]);

  useEffect(() => {
    const unsub = subscribeToRecentlyViewed((items) => {
      setRecentProducts(items);
    });
    return () => unsub();
  }, []);

  // Filter out current product if on product detail page
  const filtered = recentProducts.filter((p) => p.id !== currentProductId);

  if (filtered.length === 0) return null;

  return (
    <section className="py-8 bg-stone-50 border-t border-b border-stone-200 font-sans">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-6">
        
        {/* Header */}
        <div className="flex items-center justify-between gap-4">
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 rounded-xl bg-amber-100 text-amber-900 flex items-center justify-center">
              <History className="w-4 h-4 text-[#C81E3D]" />
            </div>
            <div>
              <h3 className="text-lg font-serif font-bold text-stone-900">Recently Viewed Products</h3>
              <p className="text-xs text-stone-500">Products you checked out earlier in this session</p>
            </div>
          </div>

          <button
            onClick={() => clearRecentlyViewed()}
            className="text-xs text-stone-500 hover:text-rose-600 flex items-center gap-1 transition-colors cursor-pointer"
            title="Clear recently viewed history"
          >
            <Trash2 className="w-3.5 h-3.5" />
            <span className="hidden sm:inline">Clear History</span>
          </button>
        </div>

        {/* Product Cards Row / Grid */}
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
          {filtered.map((product) => {
            const effectiveRating = getEffectiveProductRating(product);
            const price = typeof product.price === 'string' ? parseFloat(product.price) || 0 : product.price;

            return (
              <div
                key={product.id}
                onClick={() => onSelectProduct(product)}
                className="bg-white rounded-2xl p-3 border border-stone-200 shadow-xs hover:shadow-md hover:border-amber-300 transition-all cursor-pointer group flex flex-col justify-between"
              >
                <div className="space-y-2">
                  <div className="w-full aspect-square bg-stone-100 rounded-xl overflow-hidden 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>

                  <h4 className="text-xs font-bold text-stone-900 group-hover:text-[#C81E3D] transition-colors line-clamp-2 min-h-[32px]">
                    {product.name}
                  </h4>

                  <div className="flex items-center justify-between text-xs pt-1">
                    <span className="font-extrabold text-amber-900">
                      Rs {price.toLocaleString('en-PK')}
                    </span>

                    {effectiveRating.ratingCount > 0 ? (
                      <span className="text-[10px] font-bold text-amber-600 bg-amber-50 px-1.5 py-0.5 rounded border border-amber-200">
                        ★ {effectiveRating.averageRating}
                      </span>
                    ) : (
                      <span className="text-[10px] text-stone-400">★ 0.0</span>
                    )}
                  </div>
                </div>

                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onAddToCart(product);
                  }}
                  className="mt-3 w-full py-1.5 bg-[#1C1814] hover:bg-[#C81E3D] text-white rounded-xl text-[11px] font-bold transition-colors flex items-center justify-center gap-1.5 cursor-pointer"
                >
                  <ShoppingBag className="w-3.5 h-3.5" />
                  <span>Add</span>
                </button>
              </div>
            );
          })}
        </div>

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