import { useEffect, useState } from 'react';
import SearchBar from '../components/SearchBar';
import ListingCard from '../components/ListingCard';
import { publicService } from '../services/publicService';
import type { Listing, Category } from '../types';

export default function HomePage() {
  const [listings, setListings] = useState<Listing[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);

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

  const loadInitialData = async () => {
    setLoading(true);
    try {
      const [latestListings, cats] = await Promise.all([
        publicService.getLatestListings(),
        publicService.getCategories()
      ]);
      setListings(latestListings);
      setCategories(cats);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = async (query: string) => {
    setLoading(true);
    try {
      const results = await publicService.searchListings(query);
      setListings(results);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  const mainCategories = categories.filter(c => !c.parentId);

  return (
    <div className="min-h-screen bg-gray-50 pb-20">
      {/* Hero Section */}
      <div className="bg-primary-900 text-white py-20 px-4 relative overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-br from-primary-900 to-gray-900 opacity-90"></div>
        <div className="max-w-4xl mx-auto text-center relative z-10">
          <h1 className="text-4xl md:text-5xl font-bold mb-6">Encuentra tu próximo objetivo</h1>
          <p className="text-xl text-primary-100 mb-10">Clasificados verificados de Autos, Propiedades y más.</p>
          <div className="flex justify-center">
            <SearchBar onSearch={handleSearch} />
          </div>
        </div>
      </div>

      {/* Categories Quick Links */}
      <div className="max-w-6xl mx-auto px-4 -mt-8 relative z-20">
        <div className="bg-white rounded-xl shadow-lg p-6 flex flex-wrap justify-center gap-4 md:gap-8 border border-gray-100">
          {mainCategories.map(cat => (
            <button key={cat.id} className="flex flex-col items-center gap-2 group">
              <div className="w-12 h-12 rounded-full bg-primary-50 flex items-center justify-center text-primary-600 group-hover:bg-primary-600 group-hover:text-white transition">
                <div className="font-bold text-lg">{cat.name.charAt(0)}</div>
              </div>
              <span className="text-sm font-medium text-gray-600 group-hover:text-primary-700">{cat.name}</span>
            </button>
          ))}
        </div>
      </div>

      {/* Latest Listings */}
      <div className="max-w-6xl mx-auto px-4 mt-16">
        <h2 className="text-2xl font-bold text-gray-900 mb-8">
          {loading ? 'Cargando...' : 'Resultados Recientes'}
        </h2>

        {!loading && listings.length === 0 && (
          <div className="text-center text-gray-500 py-10">
            No se encontraron avisos con esos criterios.
          </div>
        )}

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
          {listings.map(listing => (
            <ListingCard key={listing.id} listing={listing} />
          ))}
        </div>
      </div>
    </div>
  );
}