import { searchMarketplaceProducts, listMarketplaceStores } from "@/lib/marketplace-data";
import { SearchSidebar } from "@/components/SearchSidebar";
import { Search } from "lucide-react";

export const revalidate = 0;

export default async function BuscaPage({
  searchParams,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
  const params = await searchParams;
  const q = typeof params.q === 'string' ? params.q : undefined;
  const storeId = typeof params.storeId === 'string' ? params.storeId : undefined;
  const minPrice = typeof params.minPrice === 'string' && !isNaN(Number(params.minPrice)) ? Number(params.minPrice) : undefined;
  const maxPrice = typeof params.maxPrice === 'string' && !isNaN(Number(params.maxPrice)) ? Number(params.maxPrice) : undefined;

  const [products, stores] = await Promise.all([
    searchMarketplaceProducts({ q, storeId, minPrice, maxPrice, limit: 100 }),
    listMarketplaceStores()
  ]);

  return (
    <div className="bg-gray-50 min-h-screen pb-16">
      <div className="bg-white border-b border-gray-100 py-8">
        <div className="container mx-auto px-4 lg:px-8">
          <h1 className="text-2xl lg:text-3xl font-extrabold text-gray-900 mb-2">
            {q ? `Resultados para "${q}"` : "Busca Avançada"}
          </h1>
          <p className="text-gray-500">
            {products.length} {products.length === 1 ? 'produto encontrado' : 'produtos encontrados'}
          </p>
        </div>
      </div>
      
      <div className="container mx-auto px-4 lg:px-8 py-8 flex flex-col lg:flex-row gap-8 items-start">
        <aside className="w-full lg:w-64 flex-shrink-0">
          <SearchSidebar 
            initialQuery={q} 
            initialStoreId={storeId} 
            initialMinPrice={minPrice} 
            initialMaxPrice={maxPrice} 
            stores={stores} 
          />
        </aside>
        
        <main className="flex-1">
          {products.length > 0 ? (
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4 gap-3 sm:gap-4 lg:gap-6">
              {products.map((product) => {
                const primaryImage = product.product_images?.find(img => img.is_primary)?.image_url || product.image_url;
                const fallbackImage = 'https://images.unsplash.com/photo-1542291026-7eec264c27ff?q=80&w=600&auto=format&fit=crop';
                
                let displayPrice = product.price;
                if (product.product_price_tiers && product.product_price_tiers.length > 0) {
                   const minTierPrice = Math.min(...product.product_price_tiers.map(t => t.unit_price));
                   if (minTierPrice < displayPrice) displayPrice = minTierPrice;
                }

                return (
                  <div key={product.id} className="bg-white border border-gray-100 rounded-xl overflow-hidden hover:shadow-xl hover:border-violet-200 transition-all duration-300 group flex flex-col h-full">
                    {/* Image Area */}
                    <div className="aspect-square bg-gray-50 relative overflow-hidden">
                      <img 
                        src={primaryImage || fallbackImage} 
                        alt={product.name} 
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                      />
                      
                      {/* Floating Store Badge */}
                      <a href={`/lojas/${product.store?.slug}`} className="absolute bottom-2 left-2 right-2 bg-white/90 backdrop-blur-sm rounded-lg p-1.5 flex items-center gap-2 opacity-0 translate-y-4 group-hover:opacity-100 group-hover:translate-y-0 transition-all duration-300 shadow-sm hover:bg-white z-10">
                        <div className="w-5 h-5 rounded-full bg-gray-100 overflow-hidden flex-shrink-0">
                          {product.store?.logoUrl ? (
                            <img src={product.store.logoUrl} alt="" className="w-full h-full object-cover" />
                          ) : (
                            <div className="w-full h-full flex items-center justify-center text-gray-400 text-xs font-bold">L</div>
                          )}
                        </div>
                        <span className="text-[10px] font-bold text-gray-700 truncate">
                          {product.store?.name || "Loja Parceira"}
                        </span>
                      </a>
                    </div>
                    
                    {/* Content Area */}
                    <div className="p-3 sm:p-4 flex flex-col flex-1">
                      <a href={`/produtos/${product.id}`} className="block mb-2 group-hover:text-violet-600 transition-colors">
                        <h3 className="text-sm sm:text-base font-medium text-gray-800 line-clamp-2 leading-snug">
                          {product.name}
                        </h3>
                      </a>
                      
                      <div className="mt-auto pt-2">
                        <div className="flex items-baseline gap-1">
                          <span className="text-[10px] sm:text-xs text-gray-500 font-medium">R$</span>
                          <span className="font-bold text-violet-600 text-lg sm:text-xl leading-none">
                            {displayPrice.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center py-20 bg-white rounded-3xl border border-gray-100 mt-12 text-center px-4">
              <div className="w-20 h-20 bg-gray-50 rounded-full flex items-center justify-center mb-6">
                <Search className="w-8 h-8 text-gray-400" />
              </div>
              <h2 className="text-xl font-bold text-gray-900 mb-2">Nenhum produto encontrado</h2>
              <p className="text-gray-500 max-w-md">
                Não conseguimos encontrar produtos que correspondam à sua busca. Tente ajustar os filtros ou usar outras palavras-chave.
              </p>
            </div>
          )}
        </main>
      </div>
    </div>
  );
}