import { useState, useEffect } from 'react';
import { Search } from 'lucide-react';
import { ListingGrid } from '../components/listings/ListingGrid';
import { CategorySidebar } from '../components/listings/CategorySidebar';
import { api } from '../api/client';
import type { Listing, PaginatedResponse } from '../types';

const categoryTags = ['Furniture', 'Electronics', 'Clothing', 'Books', 'Games'];

export function HomePage() {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string | undefined>();
  const [listings, setListings] = useState<Listing[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    const params = new URLSearchParams();
    params.set('pageSize', '20');
    if (selectedCategory) params.set('category', selectedCategory);
    if (searchQuery) params.set('search', searchQuery);

    api.get<PaginatedResponse<Listing>>(`/listings?${params}`)
      .then(res => setListings(res.data))
      .catch(() => setListings([]))
      .finally(() => setLoading(false));
  }, [selectedCategory, searchQuery]);

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
  };

  return (
    <div>
      {/* Hero */}
      <section className="bg-gradient-to-br from-primary-100 via-primary-50 to-pink-50 py-12 sm:py-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 text-center">
          <h1 className="text-3xl sm:text-4xl lg:text-5xl font-extrabold text-gray-900 mb-4">
            Buy & sell <span className="bg-gradient-to-r from-primary-600 to-pink-500 bg-clip-text text-transparent">second-hand</span> items online
          </h1>
          <p className="text-gray-600 text-lg mb-8 max-w-2xl mx-auto">
            Discover great deals on unique pre-loved items near you.
          </p>
          <form onSubmit={handleSearch} className="max-w-xl mx-auto mb-6">
            <div className="relative">
              <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                type="text"
                placeholder="Search for items..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-12 pr-4 py-3.5 rounded-2xl border border-gray-200 bg-white text-base shadow-sm
                  focus:border-primary-400 focus:ring-4 focus:ring-primary-100 focus:outline-none transition-all"
              />
            </div>
          </form>
          <div className="flex flex-wrap justify-center gap-2">
            {categoryTags.map(tag => (
              <button key={tag}
                onClick={() => setSelectedCategory(tag.toUpperCase().replace(/ /g, '_') === 'CLOTHING' ? 'CLOTHING' : tag.toUpperCase())}
                className="px-4 py-1.5 rounded-full bg-white/80 backdrop-blur border border-gray-200 text-sm font-medium text-gray-700 hover:bg-primary-50 hover:border-primary-200 hover:text-primary-700 transition-all cursor-pointer">
                {tag}
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* Main content */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 py-8">
        <div className="flex gap-8">
          <aside className="hidden lg:block w-56 flex-shrink-0">
            <div className="sticky top-24">
              <CategorySidebar selected={selectedCategory} onSelect={setSelectedCategory} />
            </div>
          </aside>

          <div className="flex-1 space-y-10">
            {loading ? (
              <p className="text-gray-500 text-center py-12">Loading listings...</p>
            ) : listings.length === 0 ? (
              <p className="text-gray-500 text-center py-12">No listings found.</p>
            ) : (
              <>
                <ListingGrid listings={listings.slice(0, 4)} title="Popular Items" showViewAll />
                <ListingGrid listings={listings.slice(4, 8)} title="Trending Items" showViewAll />
                {listings.length > 8 && <ListingGrid listings={listings.slice(8, 12)} title="Newly Listed" showViewAll />}
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
