"use client";


import React, { useState, useEffect, useMemo, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import { Search, Loader2 } from 'lucide-react';
import { Business, Country } from '../../types';
import BusinessCard from '../../components/BusinessCard';
import AnnuaireHero from '../../components/AnnuaireHero';
import { useUser } from '../../components/UserProvider';

const AnnuairePageContent = () => {
    const { user } = useUser();
    const [businesses, setBusinesses] = useState<Business[]>([]);
    const [featuredBusiness, setFeaturedBusiness] = useState<Business | null>(null);
    const [countries, setCountries] = useState<Country[]>([]);
    const [categories, setCategories] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [filterCategory, setFilterCategory] = useState('All');
    const [filterCountry, setFilterCountry] = useState('All');
    const [searchQuery, setSearchQuery] = useState('');
    const [locationQuery, setLocationQuery] = useState('');
    const searchParams = useSearchParams();

    // 1. Fetch Metadata (Countries & Categories)
    useEffect(() => {
        const fetchMetadata = async () => {
            try {
                const [cRes, catRes] = await Promise.all([
                    fetch('/api/countries'),
                    fetch('/api/categories')
                ]);
                const cData = await cRes.json();
                const catData = await catRes.json();
                if (Array.isArray(cData)) setCountries(cData);
                if (Array.isArray(catData)) setCategories(catData);
            } catch (e) {}
        };
        fetchMetadata();
    }, []);

    // 2. Fetch Featured Headliner once
    useEffect(() => {
        const fetchHeadliner = async () => {
            try {
                // Disable caching to ensure we get fresh data and more variety
                const res = await fetch('/api/businesses?featured=true', { 
                    cache: 'no-store',
                    headers: user ? { 'x-user-id': user.id } : {}
                });
                const data = await res.json();
                if (Array.isArray(data) && data.length > 0) {
                    // Truly random selection from the pool of featured businesses
                    const randomIndex = Math.floor(Math.random() * data.length);
                    setFeaturedBusiness(data[randomIndex]);
                }
            } catch (error) {
                console.error('Error fetching headliner:', error);
            }
        };
        fetchHeadliner();
    }, []);

    // 3. Fetch businesses from API
    useEffect(() => {
        const fetchBusinesses = async () => {
            setLoading(true);
            try {
                const params = new URLSearchParams();
                if (filterCategory !== 'All') params.append('category', filterCategory);
                if (filterCountry !== 'All') params.append('countryId', filterCountry);
                if (searchQuery) params.append('q', searchQuery);
                if (locationQuery) params.append('location', locationQuery);
                
                const res = await fetch(`/api/businesses?${params.toString()}`, {
                    headers: user ? { 'x-user-id': user.id } : {}
                });
                const data = await res.json();
                if (Array.isArray(data)) {
                    setBusinesses(data);
                }
            } catch (error) {
                console.error('Error fetching businesses:', error);
            } finally {
                setLoading(false);
            }
        };

        const timeoutId = setTimeout(fetchBusinesses, 300); // Debounce
        return () => clearTimeout(timeoutId);
    }, [filterCategory, searchQuery, filterCountry, locationQuery]);

    useEffect(() => {
        const q = searchParams.get('q');
        if (q) setSearchQuery(q);
        
        const loc = searchParams.get('location');
        if (loc) setLocationQuery(loc);
        
        const cat = searchParams.get('category');
        if (cat) setFilterCategory(cat);

        const country = searchParams.get('country');
        if (country) setFilterCountry(country);
    }, [searchParams]);

    const filteredBusinesses = businesses;

    return (
        <div>
            {/* Tête d'affiche (Headliner) - Always visible regardless of filters */}
            {featuredBusiness && <AnnuaireHero featuredBusiness={featuredBusiness} />}

            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                <div className="flex flex-col md:flex-row gap-8">
                    {/* Filters Sidebar */}
                    <div className="w-full md:w-64 flex-shrink-0">
                        <div className="bg-white p-6 rounded-xl shadow-sm border border-gray-100 sticky top-24">
                            <h3 className="font-bold text-lg mb-4 flex items-center"><Search className="w-4 h-4 mr-2" /> Filtres</h3>

                            <div className="mb-6">
                                <label className="block text-sm font-medium text-gray-700 mb-2">Recherche</label>
                                <input
                                    type="text"
                                    value={searchQuery}
                                    onChange={(e) => setSearchQuery(e.target.value)}
                                    className="w-full border-gray-300 rounded-md shadow-sm focus:ring-brand-500 focus:border-brand-500 sm:text-sm p-2 border"
                                    placeholder="Nom, mot-clé..."
                                />
                            </div>

                            <div className="mb-6">
                                <label className="block text-sm font-medium text-gray-700 mb-2">Ville / Localisation</label>
                                <input
                                    type="text"
                                    value={locationQuery}
                                    onChange={(e) => setLocationQuery(e.target.value)}
                                    className="w-full border-gray-300 rounded-md shadow-sm focus:ring-brand-500 focus:border-brand-500 sm:text-sm p-2 border"
                                    placeholder="Ex: Abidjan, Dakar..."
                                />
                            </div>

                            <div className="mb-6">
                                <label className="block text-sm font-medium text-gray-700 mb-2">Pays</label>
                                <select
                                    value={filterCountry}
                                    onChange={(e) => setFilterCountry(e.target.value)}
                                    className="w-full border-gray-300 rounded-md shadow-sm focus:ring-brand-500 focus:border-brand-500 sm:text-sm p-2 border"
                                >
                                    <option value="All">Tous les pays</option>
                                    {countries.map(c => (
                                        <option key={c.id} value={c.id}>{c.flag} {c.name}</option>
                                    ))}
                                </select>
                            </div>

                            <div className="mb-6">
                                <label className="block text-sm font-medium text-gray-700 mb-2">Catégorie</label>
                                <div className="space-y-1 max-h-60 overflow-y-auto pr-1">
                                    <div className="flex items-center">
                                        <input
                                            id="cat-all"
                                            name="category"
                                            type="radio"
                                            checked={filterCategory === 'All'}
                                            onChange={() => setFilterCategory('All')}
                                            className="focus:ring-brand-500 h-4 w-4 text-brand-600 border-gray-300"
                                        />
                                        <label htmlFor="cat-all" className="ml-3 text-sm text-gray-600">Toutes</label>
                                    </div>
                                    {categories.map(cat => (
                                        <div key={cat.id} className="flex items-center">
                                            <input
                                                id={`cat-${cat.id}`}
                                                name="category"
                                                type="radio"
                                                checked={filterCategory === cat.id || filterCategory === cat.name}
                                                onChange={() => setFilterCategory(cat.id)}
                                                className="focus:ring-brand-500 h-4 w-4 text-brand-600 border-gray-300"
                                            />
                                            <label htmlFor={`cat-${cat.id}`} className="ml-3 text-sm text-gray-600 truncate" title={cat.name}>{cat.name}</label>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Results Grid */}
                    <div className="flex-1">
                        <div className="mb-4 flex justify-between items-center">
                            <h1 className="text-2xl font-bold font-serif text-gray-900">Annuaire des entreprises</h1>
                            <span className="text-sm text-gray-500">{filteredBusinesses.length} résultats</span>
                        </div>

                        {loading ? (
                            <div className="flex flex-col items-center justify-center py-20 bg-white rounded-xl border border-gray-100 shadow-sm">
                                <Loader2 className="w-12 h-12 text-brand-600 animate-spin mb-4" />
                                <p className="text-gray-500 font-medium">Chargement des entreprises...</p>
                            </div>
                        ) : filteredBusinesses.length > 0 ? (
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                                {filteredBusinesses.map(biz => (
                                    <BusinessCard key={biz.id} business={biz} />
                                ))}
                            </div>
                        ) : (
                            <div className="text-center py-20 bg-white rounded-xl border border-gray-100 border-dashed">
                                <div className="mx-auto h-12 w-12 text-gray-400">
                                    <Search className="h-12 w-12" />
                                </div>
                                <h3 className="mt-2 text-sm font-medium text-gray-900">Aucun résultat</h3>
                                <p className="mt-1 text-sm text-gray-500">Essayez d'ajuster vos filtres de recherche.</p>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

const AnnuairePage = () => {
    return (
        <Suspense fallback={<div className="min-h-screen flex items-center justify-center">Chargement...</div>}>
            <AnnuairePageContent />
        </Suspense>
    );
};

export default AnnuairePage;
