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, CardContent } 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 { Select } from '@/components/ui/select';
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 } from 'lucide-react';
import { logger } from '@/utils/logger';
import { parseApiError } from '@/utils/apiErrorHandler';
import { Badge } from '@/components/ui/badge';
import { Pagination } from '@/components/navigation/Pagination';

// FE-PAGE-006: Complete Marketplace page implementation

export function MarketplaceHome() {
  const [products, setProducts] = useState<Product[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [queryError, setQueryError] = useState<Error | null>(null);
  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);

  // FE-PAGE-006: Filtering state
  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();

  // FE-PAGE-006: Load products with filters and pagination
  const loadProducts = async () => {
    try {
      setIsLoading(true);
      setQueryError(null);
      const filters: any = {
        status: 'active', // Only show active products
      };

      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 errorMessage =
        error instanceof Error
          ? error.message
          : 'Failed to load marketplace products';
      setQueryError(new Error(errorMessage));
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    loadProducts();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [page, limit, productType, priceRange, searchQuery]);

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

  // CRITIQUE FIX #70: Gestion d'erreur améliorée pour purchaseProduct
  // Action 3.4.1.3: Store mutation for retry
  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) {
      // CRITIQUE FIX #70: Gestion d'erreur améliorée avec message détaillé
      const apiError = parseApiError(error);
      logger.error("Erreur lors de l'achat du produit", {
        error: apiError.message,
        productId: product.id,
      });
      setMutationError(new Error(apiError.message));
    } finally {
      setPurchasingProductId(null);
    }
  };

  // Action 3.4.1.3: Retry handler for failed mutations
  const handleRetry = async () => {
    if (!lastMutationRef.current || retryCount >= 3) return;

    setRetryCount((prev) => prev + 1);
    try {
      await lastMutationRef.current();
    } catch (error) {
      // Error will be handled by the mutation function
    }
  };

  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="container mx-auto px-4 py-8">
        <div className="flex items-center justify-center min-h-[400px]">
          <LoadingSpinner />
        </div>
      </div>
    );
  }

  if (queryError && products.length === 0) {
    return (
      <div className="container mx-auto px-4 py-8">
        <ErrorDisplay
          error={queryError}
          variant="card"
          severity="error"
          context={{
            action: 'fetching marketplace products',
            resource: 'marketplace',
          }}
          onRetry={loadProducts}
        />
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      {mutationError && (
        <ErrorDisplay
          error={mutationError}
          variant="banner"
          severity="error"
          context={{
            action: 'purchasing product',
            resource: 'marketplace',
          }}
          onRetry={retryCount < 3 ? handleRetry : undefined}
          onDismiss={() => {
            setMutationError(null);
            setRetryCount(0);
            lastMutationRef.current = null;
          }}
        />
      )}
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold mb-2">Marketplace</h1>
          <p className="text-muted-foreground">
            Discover and purchase music products, samples, and licenses
          </p>
        </div>
        <Button
          onClick={() => setIsCartOpen(true)}
          className="relative"
          variant="outline"
        >
          <ShoppingCart className="mr-2 h-4 w-4" />
          Cart
          {getItemCount() > 0 && (
            <Badge className="ml-2 bg-blue-600">{getItemCount()}</Badge>
          )}
        </Button>
      </div>

      {/* FE-PAGE-006: Search and Filters */}
      <Card className="mb-6">
        <CardContent className="p-4">
          <div className="space-y-4">
            <div className="flex items-center gap-4">
              <div className="relative flex-1">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                <Input
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="Search products..."
                  className="pl-10"
                />
              </div>
              <Button
                variant="outline"
                onClick={() => setShowFilters(!showFilters)}
              >
                <Filter className="mr-2 h-4 w-4" />
                Filters
                {hasActiveFilters && (
                  <Badge className="ml-2" variant="secondary">
                    Active
                  </Badge>
                )}
              </Button>
              {hasActiveFilters && (
                <Button variant="ghost" onClick={handleClearFilters}>
                  <X className="mr-2 h-4 w-4" />
                  Clear
                </Button>
              )}
            </div>

            {showFilters && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-4 border-t">
                <div className="space-y-2">
                  <Label htmlFor="product-type">Product Type</Label>
                  <Select
                    options={[
                      { value: '', label: 'All Types' },
                      { value: 'track', label: 'Track' },
                      { value: 'pack', label: 'Pack' },
                      { value: 'service', label: 'Service' },
                    ]}
                    value={productType}
                    onChange={(value) =>
                      setProductType(
                        (Array.isArray(value) ? value[0] : value) as
                          | ProductType
                          | '',
                      )
                    }
                    name="product-type"
                  />
                </div>
                <div className="space-y-2">
                  <Label>
                    Price Range: €{priceRange[0]} - €{priceRange[1]}
                  </Label>
                  <Slider
                    min={0}
                    max={1000}
                    step={10}
                    value={priceRange}
                    onValueChange={(value) =>
                      setPriceRange([value[0], value[1]])
                    }
                    className="w-full"
                  />
                </div>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* FE-PAGE-006: Results count */}
      {!isLoading && (
        <div className="mb-4 text-sm text-muted-foreground">
          Showing {products.length} of {total} products
        </div>
      )}

      {products.length === 0 && !isLoading ? (
        <Card>
          <CardContent className="pt-6">
            <div className="text-center py-8">
              <p className="text-muted-foreground">
                No products found. Try adjusting your filters.
              </p>
            </div>
          </CardContent>
        </Card>
      ) : (
        <>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-6">
            {products.map((product) => (
              <ProductCard
                key={product.id}
                product={product}
                onPurchase={handlePurchase}
                onAddToCart={handleAddToCart}
                isPurchasing={purchasingProductId === product.id}
              />
            ))}
          </div>

          {/* FE-COMP-006: Pagination component */}
          <Pagination
            currentPage={page}
            totalPages={totalPages}
            onPageChange={setPage}
            totalItems={total}
            itemsPerPage={limit}
            showItemsInfo={true}
            className="mt-6"
          />
        </>
      )}

      {/* FE-PAGE-006: Cart Dialog */}
      <Cart isOpen={isCartOpen} onClose={() => setIsCartOpen(false)} />
    </div>
  );
}
