import { useState, useEffect, useRef } from 'react';
import { marketplaceService } from '@/services/marketplaceService';
import { ProductCard } from '@/features/marketplace/components/ProductCard';
import { Product, ProductType } from '@/types/marketplace';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { Card } from '@/components/ui/card';
import { useToast } from '@/hooks/useToast';
import { Input } from '@/components/ui/input';
import { ErrorDisplay } from '@/components/ui/ErrorDisplay';
import { Button } from '@/components/ui/button';
import { Slider } from '@/components/ui/slider';
import { Label } from '@/components/ui/label';
import { Cart } from '@/features/marketplace/components/Cart';
import { useCartStore } from '@/stores/cartStore';
import { Search, ShoppingCart, Filter, X, ShoppingBag } from 'lucide-react';
import { parseApiError } from '@/utils/apiErrorHandler';
import { Badge } from '@/components/ui/badge';
import { Pagination } from '@/components/navigation/Pagination';
import { cn } from '@/lib/utils';

export function MarketplaceHome() {
  const [products, setProducts] = useState<Product[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [mutationError, setMutationError] = useState<Error | null>(null);
  const [purchasingProductId, setPurchasingProductId] = useState<string | null>(null);
  const [retryCount, setRetryCount] = useState(0);
  const lastMutationRef = useRef<(() => Promise<void>) | null>(null);
  const [isCartOpen, setIsCartOpen] = useState(false);
  const [page, setPage] = useState(1);
  const [limit] = useState(12);
  const [totalPages, setTotalPages] = useState(1);
  const [total, setTotal] = useState(0);

  const isLoadingRef = useRef(false);

  const [searchQuery, setSearchQuery] = useState('');
  const [productType, setProductType] = useState<ProductType | ''>('');
  const [priceRange, setPriceRange] = useState<[number, number]>([0, 1000]);
  const [showFilters, setShowFilters] = useState(false);

  const toast = useToast();
  const { addItem, getItemCount } = useCartStore();

  const loadProducts = async () => {
    if (isLoadingRef.current) return;
    try {
      isLoadingRef.current = true;
      setIsLoading(true);
      const filters: any = { status: 'active' };

      if (productType) filters.product_type = productType;
      if (priceRange[0] > 0) filters.min_price = priceRange[0];
      if (priceRange[1] < 1000) filters.max_price = priceRange[1];
      if (searchQuery.trim()) filters.search = searchQuery.trim();

      const response = await marketplaceService.fetchProducts(filters, { page, limit });
      setProducts(response.products);
      setTotal(response.total);
      setTotalPages(response.total_pages);
    } catch (error) {
      const apiError = parseApiError(error);
      const errorMessage = apiError.message || 'Failed to load marketplace products';
      let statusCode = 0;
      // @ts-ignore - Safely checking for httpStatus property
      if (error && typeof error === 'object' && 'httpStatus' in error) statusCode = error.httpStatus;

      if (statusCode === 500) {
        setProducts([]);
        setTotal(0);
        setTotalPages(1);
      } else {
        toast.error(errorMessage);
        // Error handling was logging potentially unused error state
      }
    } finally {
      setIsLoading(false);
      isLoadingRef.current = false;
    }
  };

  const priceRangeString = JSON.stringify(priceRange);
  useEffect(() => { loadProducts(); }, [page, limit, productType, priceRangeString, searchQuery]);

  const handleAddToCart = (product: Product) => {
    addItem(product);
    toast.success(`${product.title} added to cart`);
  };

  const handlePurchase = async (product: Product) => {
    const performMutation = async () => {
      await marketplaceService.purchaseProduct(product.id);
      toast.success(`Successfully purchased ${product.title}`);
      setMutationError(null);
      setRetryCount(0);
      lastMutationRef.current = null;
    };

    lastMutationRef.current = performMutation;
    setPurchasingProductId(product.id);
    setMutationError(null);

    try { await performMutation(); }
    catch (error: unknown) { setMutationError(new Error(parseApiError(error).message)); }
    finally { setPurchasingProductId(null); }
  };

  const handleRetry = async () => {
    if (!lastMutationRef.current || retryCount >= 3) return;
    setRetryCount((prev) => prev + 1);
    try { await lastMutationRef.current(); } catch (error) { }
  };

  const handleClearFilters = () => {
    setSearchQuery('');
    setProductType('');
    setPriceRange([0, 1000]);
  };

  const hasActiveFilters = searchQuery || productType || priceRange[0] > 0 || priceRange[1] < 1000;

  if (isLoading && products.length === 0) {
    return <div className="flex items-center justify-center min-h-screen"><LoadingSpinner /></div>;
  }

  return (
    <div className="min-h-screen pb-24 relative">
      {/* Background Ambience */}
      <div className="absolute inset-x-0 top-0 h-96 bg-gradient-to-b from-purple-900/20 via-background to-background pointer-events-none" />

      <div className="container mx-auto px-4 py-8 relative z-10">
        {mutationError && (
          <ErrorDisplay
            error={mutationError}
            variant="banner"
            severity="error"
            onRetry={retryCount < 3 ? handleRetry : undefined}
            onDismiss={() => { setMutationError(null); setRetryCount(0); lastMutationRef.current = null; }}
          />
        )}

        <div className="flex items-end justify-between mb-8 gap-4">
          <div>
            <h1 className="text-4xl md:text-5xl font-display font-bold mb-2 text-transparent bg-clip-text bg-gradient-to-r from-white to-white/60">Marketplace</h1>
            <p className="text-lg text-muted-foreground">Premium assets for your next masterpiece.</p>
          </div>

          <Button onClick={() => setIsCartOpen(true)} className="relative h-12 px-6 rounded-full shadow-glow-cyan" variant="default">
            <ShoppingCart className="mr-2 h-5 w-5" />
            <span className="font-bold">Cart</span>
            {getItemCount() > 0 && (
              <Badge className="ml-2 bg-white text-primary font-bold shadow-none hover:bg-white">{getItemCount()}</Badge>
            )}
          </Button>
        </div>

        {/* Glass Filters Bar */}
        <Card variant="glass" className="mb-8 p-4 sticky top-24 z-20 backdrop-blur-xl bg-black/40 border-white/10 shadow-xl">
          <div className="flex flex-col md:flex-row gap-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <Input
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search tracks, packs, services..."
                className="pl-10 bg-white/5 border-white/10 text-white placeholder:text-white/30 focus:bg-black/40 transition-all rounded-xl"
              />
            </div>
            <div className="flex gap-2">
              <Button variant="outline" onClick={() => setShowFilters(!showFilters)} className={cn("border-white/10 hover:bg-white/5", showFilters && "bg-primary/20 border-primary/50 text-white")}>
                <Filter className="w-4 h-4 mr-2" /> Filters
                {hasActiveFilters && <div className="ml-2 w-2 h-2 rounded-full bg-primary shadow-[0_0_5px_var(--color-primary)]" />}
              </Button>
              {hasActiveFilters && (
                <Button variant="ghost" onClick={handleClearFilters} className="text-muted-foreground hover:text-white">
                  <X className="w-4 h-4 mr-2" /> Clear
                </Button>
              )}
            </div>
          </div>

          {/* Expanded Filters */}
          {showFilters && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-8 pt-6 mt-4 border-t border-white/5 animate-slide-down">
              <div className="space-y-4">
                <Label className="text-xs uppercase tracking-widest text-muted-foreground">Product Type</Label>
                <div className="flex gap-2">
                  {['track', 'pack', 'service'].map(type => (
                    <Button
                      key={type}
                      variant={productType === type ? 'default' : 'outline'}
                      onClick={() => setProductType(productType === type ? '' : type as ProductType)}
                      size="sm"
                      className="capitalize rounded-full px-6"
                    >
                      {type}
                    </Button>
                  ))}
                </div>
              </div>
              <div className="space-y-4">
                <div className="flex justify-between">
                  <Label className="text-xs uppercase tracking-widest text-muted-foreground">Price Range</Label>
                  <span className="text-sm font-mono text-primary">€{priceRange[0]} - €{priceRange[1]}</span>
                </div>
                <Slider min={0} max={1000} step={10} value={priceRange} onValueChange={(val) => setPriceRange([val[0], val[1]])} className="py-4" />
              </div>
            </div>
          )}
        </Card>

        {/* Results */}
        {!isLoading && (
          <div className="mb-6 flex items-center gap-2 text-sm text-muted-foreground">
            <div className="w-1.5 h-1.5 rounded-full bg-primary" />
            <span>Found {total} results</span>
          </div>
        )}

        {products.length === 0 && !isLoading ? (
          <div className="flex flex-col items-center justify-center py-20 text-center opacity-60">
            <ShoppingBag className="w-16 h-16 mb-4 text-muted-foreground/50" />
            <h3 className="text-xl font-bold mb-2">No items found</h3>
            <p className="text-muted-foreground">Try adjusting your signal filters.</p>
          </div>
        ) : (
          <>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 mb-8">
              {products.map(product => (
                <ProductCard
                  key={product.id}
                  product={product}
                  onPurchase={handlePurchase}
                  onAddToCart={handleAddToCart}
                  isPurchasing={purchasingProductId === product.id}
                />
              ))}
            </div>
            <Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} totalItems={total} itemsPerPage={limit} showItemsInfo={true} />
          </>
        )}

        <Cart isOpen={isCartOpen} onClose={() => setIsCartOpen(false)} />
      </div>
    </div>
  );
}
