import React, { useEffect, useState } from 'react';
import { marketplaceService } from '@/services/marketplaceService';
import { Product } from '@/types/marketplace';
import { ProductCard } from '@/features/marketplace/components/ProductCard';
import { useToast } from '@/hooks/useToast';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { Button } from '@/components/ui/button'; // Assuming we have a generic Button
import { AlertCircle } from 'lucide-react';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';

export default function MarketplaceHome() {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [purchasingId, setPurchasingId] = useState<string | null>(null);
  const { toast } = useToast();

  const fetchProducts = async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await marketplaceService.fetchProducts({ status: 'active' });
      setProducts(data);
    } catch (err) {
      setError('Failed to load products. Please try again later.');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

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

  const handlePurchase = async (product: Product) => {
    setPurchasingId(product.id);
    try {
      await marketplaceService.purchaseProduct(product.id);
      toast({
        title: 'Purchase Successful',
        description: `You have successfully purchased "${product.title}". Check your library.`,
        variant: 'default', // or 'success' if available
      });
      // Optionally redirect or update UI
    } catch (err) {
      toast({
        title: 'Purchase Failed',
        description: 'An error occurred during the purchase. Please try again.',
        variant: 'destructive',
      });
      console.error(err);
    } finally {
      setPurchasingId(null);
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-full">
        <LoadingSpinner />
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-4">
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>Error</AlertTitle>
          <AlertDescription>{error}</AlertDescription>
        </Alert>
        <Button className="mt-4" onClick={fetchProducts}>Retry</Button>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-6">
      <h1 className="text-3xl font-bold mb-6">Marketplace</h1>
      
      {products.length === 0 ? (
        <div className="text-center text-muted-foreground py-12">
          No products available at the moment.
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
          {products.map((product) => (
            <ProductCard 
              key={product.id} 
              product={product} 
              onPurchase={handlePurchase}
              isPurchasing={purchasingId === product.id}
            />
          ))}
        </div>
      )}
    </div>
  );
}
