import React, { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { SearchInput } from '../ui/input';
import { Loader2, SlidersHorizontal } from 'lucide-react';
import { Product } from '../../types';
import { useToast } from '../../context/ToastContext';
import { useCart } from '../../context/CartContext';
import { ProductCard } from '../marketplace/ProductCard';
import { ProductDetailView } from '../marketplace/ProductDetailView';
import { marketplaceService } from '../../services/marketplaceService';
import { logger } from '@/utils/logger';

export const MarketplaceView: React.FC = () => {
  const { addToast } = useToast();
  const { addToCart } = useCart();

  const [loading, setLoading] = useState(true);
  const [products, setProducts] = useState<Product[]>([]);
  const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);

  // Filters State
  const [activeCategory, setActiveCategory] = useState('All');
  const [searchQuery, setSearchQuery] = useState('');
  const [filtersOpen, setFiltersOpen] = useState(false);
  const [playingPreview, setPlayingPreview] = useState<string | null>(null);

  useEffect(() => {
    loadProducts();
  }, []);

  const loadProducts = async () => {
    setLoading(true);
    try {
      const fetchedProducts = await marketplaceService.listProducts({
        status: 'active',
      });
      setProducts(fetchedProducts.products);
    } catch (error) {
      logger.error('Failed to load products', {
        error: error instanceof Error ? error.message : String(error),
        stack: error instanceof Error ? error.stack : undefined,
      });
      addToast('Failed to load products', 'error');
    } finally {
      setLoading(false);
    }
  };

  const togglePreview = (id: string) => {
    if (playingPreview === id) {
      setPlayingPreview(null);
    } else {
      setPlayingPreview(id);
      addToast('Previewing audio...', 'info');
    }
  };

  // Filter Logic
  const filteredProducts = products.filter((p) => {
    // Basic category filter (mapping our UI categories to Product types)
    const matchCat =
      activeCategory === 'All' ||
      (activeCategory === 'Samples' && p.product_type === 'pack') ||
      (activeCategory === 'Beats' && p.product_type === 'track');
    const matchSearch = p.title
      .toLowerCase()
      .includes(searchQuery.toLowerCase());
    return matchCat && matchSearch;
  });

  if (selectedProduct) {
    return (
      <ProductDetailView
        product={selectedProduct}
        onBack={() => setSelectedProduct(null)}
        onAddToCart={addToCart}
        similarProducts={products
          .filter((p) => p.id !== selectedProduct.id)
          .slice(0, 3)}
      />
    );
  }

  return (
    <div className="animate-fadeIn min-h-screen pb-20 relative">
      {/* Header */}
      <div className="flex flex-col md:flex-row justify-between items-end mb-8 gap-4">
        <div>
          <h2 className="text-3xl font-display font-bold text-white mb-2">
            MARKETPLACE
          </h2>
          <p className="text-gray-400 font-mono text-sm">
            Discover premium sounds and tools.
          </p>
        </div>

        <div className="flex items-center gap-3 w-full md:w-auto">
          <div className="relative flex-1 md:w-64">
            <SearchInput
              placeholder="Search sounds..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
          </div>
        </div>
      </div>

      {/* Categories Bar */}
      <div className="flex flex-col md:flex-row justify-between items-center gap-4 mb-8 bg-kodo-ink/50 p-2 rounded-xl border border-kodo-steel/50">
        <div className="flex items-center gap-2 overflow-x-auto w-full md:w-auto p-1 no-scrollbar">
          <Button
            variant={filtersOpen ? 'primary' : 'ghost'}
            size="sm"
            icon={<SlidersHorizontal className="w-4 h-4" />}
            onClick={() => setFiltersOpen(!filtersOpen)}
          >
            FILTERS
          </Button>
          <div className="h-6 w-px bg-kodo-steel mx-2"></div>
          {['All', 'Samples', 'Beats', 'Presets'].map((cat) => (
            <button
              key={cat}
              onClick={() => setActiveCategory(cat)}
              className={`px-4 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${activeCategory === cat ? 'bg-white text-black' : 'text-gray-400 hover:text-white hover:bg-white/5'}`}
            >
              {cat}
            </button>
          ))}
        </div>
      </div>

      <div className="flex gap-8">
        {/* Sidebar Filters */}
        {filtersOpen && (
          <div className="w-64 flex-shrink-0 space-y-8 hidden lg:block animate-slideInLeft">
            <Card variant="default">
              <h3 className="text-xs font-bold text-gray-500 uppercase tracking-widest mb-4">
                Price
              </h3>
              <div className="space-y-2">
                <label className="flex items-center gap-2 text-sm text-gray-300">
                  <input type="checkbox" /> Under $20
                </label>
                <label className="flex items-center gap-2 text-sm text-gray-300">
                  <input type="checkbox" /> $20 - $50
                </label>
              </div>
            </Card>
          </div>
        )}

        {/* Product Grid */}
        <div className="flex-1">
          {loading ? (
            <div className="flex justify-center py-20">
              <Loader2 className="w-8 h-8 text-kodo-cyan animate-spin" />
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-6">
              {filteredProducts.map((product) => (
                <ProductCard
                  key={product.id}
                  product={product}
                  onClick={setSelectedProduct}
                  onAddToCart={(p) => addToCart(p, p.licenses?.[0])}
                  onPreview={togglePreview}
                  isPlayingPreview={playingPreview === product.id}
                />
              ))}
            </div>
          )}
          {!loading && filteredProducts.length === 0 && (
            <div className="text-center py-20 text-gray-500">
              <p>No products found matching your filters.</p>
              <Button
                variant="ghost"
                className="mt-4"
                onClick={() => {
                  setActiveCategory('All');
                  setSearchQuery('');
                }}
              >
                Clear Filters
              </Button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};
