import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { productsApi, categoriesApi, storesApi } from "@/lib/api";
import logoUrl from "@assets/assets_task_01k3qp9hccec89tp5ht8ee88x5_1756363038_img_1-removebg-preview (1)_1756364677577.png";
import Header from "@/components/layout/header";
import CategoryNav from "@/components/category/category-nav";
import ProductGrid from "@/components/product/product-grid";
import StoreCard from "@/components/store/store-card";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Category, Product, Store } from "@/types";
import { Package, ShieldCheck, Star, Truck, CreditCard, HeadphonesIcon } from "lucide-react";
import { LoadingSpinner } from "@/components/ui/spinner";

export default function Home() {
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedCategory, setSelectedCategory] = useState<string>("");

  const { data: categories = [], isLoading: categoriesLoading } = useQuery({
    queryKey: ['/api/categories'],
    queryFn: () => categoriesApi.getAll(),
  });

  const { data: featuredProducts = [], isLoading: featuredLoading } = useQuery({
    queryKey: ['/api/products/featured'],
    queryFn: () => productsApi.getFeatured(),
  });

  const { data: stores = [], isLoading: storesLoading } = useQuery({
    queryKey: ['/api/stores'],
    queryFn: () => storesApi.getAll(),
  });

  const { data: searchResults = [], isLoading: searchLoading } = useQuery({
    queryKey: ['/api/products', { search: searchQuery, category: selectedCategory }],
    queryFn: () => productsApi.getAll({ 
      ...(searchQuery && { search: searchQuery }),
      ...(selectedCategory && { category: selectedCategory })
    }),
    enabled: !!(searchQuery || selectedCategory),
  });

  const showingResults = searchQuery || selectedCategory;
  const displayProducts = showingResults ? searchResults : featuredProducts;
  const isProductsLoading = showingResults ? searchLoading : featuredLoading;

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
      <Header searchQuery={searchQuery} setSearchQuery={setSearchQuery} />

      {/* Hero Section - Modern Style */}
      <section className="py-2" data-testid="hero-section">
        <div className="max-w-full mx-auto px-2 sm:px-3 lg:px-4">
          {/* Hero Banner Card - Modern Style */}
          <div className="bg-white/70 backdrop-blur-sm rounded-3xl p-4 mb-3 shadow-sm border border-white/50">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 items-center">
              <div>
                <div className="flex items-center mb-4" data-testid="hero-title">
                  <img 
                    src={logoUrl} 
                    alt="Shoposphere" 
                    className="h-12 w-auto mr-4"
                  />
                  <h1 className="text-2xl lg:text-3xl font-semibold text-gray-800">
                    Discover Amazing Products
                    <br />
                    <span className="text-lg text-gray-500 font-normal">from trusted sellers</span>
                  </h1>
                </div>
                <div className="flex space-x-3">
                  <Button className="bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600 text-white border-0 rounded-2xl px-8 py-3 font-medium shadow-sm hover:shadow-md transition-all duration-300" data-testid="browse-products">
                    Shop now
                  </Button>
                  <Button variant="outline" className="border-gray-200 text-gray-600 hover:bg-gray-50 rounded-2xl px-8 py-3 font-medium" data-testid="view-stores">
                    Learn more
                  </Button>
                </div>
              </div>
              <div className="hidden lg:block">
                <div className="bg-gradient-to-br from-purple-100 to-blue-100 rounded-3xl p-8 text-center">
                  <Package className="h-16 w-16 mx-auto mb-4 text-purple-500" />
                  <h3 className="text-xl font-semibold text-gray-800 mb-2">Fast Delivery</h3>
                  <p className="text-gray-600">Get your orders delivered quickly</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Category Navigation */}
      <section className="amazon-section py-3" data-testid="category-section">
        <div className="max-w-6xl mx-auto px-2 sm:px-3 lg:px-4">
          {categoriesLoading ? (
            <div className="flex flex-col items-center">
              <LoadingSpinner text="Loading categories..." />
              <div className="flex justify-center space-x-8 mt-4">
                {[...Array(6)].map((_, i) => (
                  <div key={i} className="flex flex-col items-center">
                    <Skeleton className="w-16 h-16 rounded-full mb-2" />
                    <Skeleton className="w-16 h-4" />
                  </div>
                ))}
              </div>
            </div>
          ) : (
            <CategoryNav 
              categories={categories}
              selectedCategory={selectedCategory}
              onCategorySelect={setSelectedCategory}
            />
          )}
        </div>
      </section>

      {/* Products Section */}
      <section className="py-6" data-testid="products-section">
        <div className="max-w-7xl mx-auto px-3 sm:px-4 lg:px-6">
          <div className="text-center mb-8">
            <h2 className="text-3xl font-semibold text-gray-800 mb-4" data-testid="products-title">
              {showingResults ? 'Search Results' : 'Featured Products'}
            </h2>
            <p className="text-gray-500 max-w-2xl mx-auto text-lg" data-testid="products-subtitle">
              {showingResults ? 
                `${displayProducts.length} products found` :
                'Discover our handpicked selection of the best products from trusted sellers'
              }
            </p>
          </div>

          {isProductsLoading ? (
            <div className="flex flex-col items-center">
              <LoadingSpinner text={showingResults ? "Searching products..." : "Loading featured products..."} />
              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3 sm:gap-4 md:gap-5 mt-6 w-full">
                {[...Array(12)].map((_, i) => (
                  <div key={i} className="glass-card rounded-2xl p-4">
                    <Skeleton className="aspect-square w-full mb-4 rounded-xl" />
                    <Skeleton className="h-4 w-3/4 mb-2" />
                    <Skeleton className="h-4 w-1/2 mb-2" />
                    <Skeleton className="h-6 w-1/4" />
                  </div>
                ))}
              </div>
            </div>
          ) : (
            <ProductGrid products={displayProducts} />
          )}

        </div>
      </section>

      {/* All Stores Section */}
      <section className="amazon-section py-6" data-testid="stores-section">
        <div className="max-w-7xl mx-auto px-2 sm:px-3 lg:px-4">
          <div className="text-center mb-6">
            <h2 className="text-3xl font-bold text-gray-900 mb-4" data-testid="stores-title">
              All Stores
            </h2>
            <p className="text-gray-600 max-w-2xl mx-auto" data-testid="stores-subtitle">
              Explore our network of verified sellers and their unique collections
            </p>
          </div>

          {storesLoading ? (
            <div className="flex flex-col items-center">
              <LoadingSpinner text="Loading stores..." />
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mt-6 w-full">
                {[...Array(6)].map((_, i) => (
                  <div key={i} className="glass-card rounded-2xl p-6">
                    <Skeleton className="h-32 w-full mb-4 rounded-xl" />
                    <div className="flex items-center space-x-4">
                      <Skeleton className="w-16 h-16 rounded-full" />
                      <div className="flex-1">
                        <Skeleton className="h-6 w-3/4 mb-2" />
                        <Skeleton className="h-4 w-full" />
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ) : stores.length > 0 ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {stores.map((store: Store) => (
                <StoreCard key={store.id} store={store} />
              ))}
            </div>
          ) : (
            <div className="text-center py-12">
              <p className="text-muted-foreground" data-testid="no-stores">
                No stores available at the moment.
              </p>
            </div>
          )}
        </div>
      </section>

    </div>
  );
}
