import { useState, useEffect } from 'react'
import { productService } from '../services/productService'
import { LocationPicker } from '../components/LocationPicker'
import { ProductCard } from '../components/ProductCard'
import { ProductWithDistance } from '../types/product'
import { useDebounce } from '../hooks/useDebounce' // Assuming this hook exists or I'll generic implement it

const ProductSearch = () => {
    const [lat, setLat] = useState<number>(-16.3285)
    const [lng, setLng] = useState<number>(-48.9534)
    const [search, setSearch] = useState('')
    const [maxDistance, setMaxDistance] = useState<number>(10)
    const [products, setProducts] = useState<ProductWithDistance[]>([])
    const [loading, setLoading] = useState(false)
    const [total, setTotal] = useState(0)

    // Debounce search term
    const [debouncedSearch, setDebouncedSearch] = useState(search)
    useEffect(() => {
        const timer = setTimeout(() => setDebouncedSearch(search), 500)
        return () => clearTimeout(timer)
    }, [search])

    useEffect(() => {
        const fetchProducts = async () => {
            setLoading(true)
            try {
                const data = await productService.search({
                    lat,
                    lng,
                    search: debouncedSearch,
                    max_distance: maxDistance,
                    page: 1,
                    page_size: 50,
                })
                setProducts(data.products)
                setTotal(data.total)
            } catch (err) {
                console.error('Failed to fetch products', err)
            } finally {
                setLoading(false)
            }
        }

        fetchProducts()
    }, [lat, lng, debouncedSearch, maxDistance])

    const handleLocationSelect = (newLat: number, newLng: number) => {
        setLat(newLat)
        setLng(newLng)
    }

    const addToCart = (product: ProductWithDistance) => {
        console.log('Added to cart:', product)
        // Implement cart logic later
        alert(`Adicionado ao carrinho: ${product.name}`)
    }

    return (
        <div className="container mx-auto px-4 py-8">
            <h1 className="text-3xl font-bold mb-6 text-gray-800">Encontre Medicamentos Próximos</h1>

            <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
                {/* Filters & Map */}
                <div className="lg:col-span-1 space-y-6">
                    <div className="bg-white p-4 rounded-lg shadow border border-gray-200">
                        <h2 className="text-lg font-semibold mb-3">Sua Localização</h2>
                        <LocationPicker
                            initialLat={lat}
                            initialLng={lng}
                            onLocationSelect={handleLocationSelect}
                        />
                        <p className="text-xs text-gray-500 mt-2">
                            Clique no mapa para ajustar sua localização.
                        </p>
                    </div>

                    <div className="bg-white p-4 rounded-lg shadow border border-gray-200 space-y-4">
                        <h2 className="text-lg font-semibold">Filtros</h2>

                        <div>
                            <label className="block text-sm font-medium text-gray-700">Busca</label>
                            <input
                                type="text"
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                placeholder="Nome do medicamento..."
                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm p-2 border"
                            />
                        </div>

                        <div>
                            <label className="block text-sm font-medium text-gray-700">
                                Raio de busca: <span className="text-primary font-bold">{maxDistance} km</span>
                            </label>
                            <input
                                type="range"
                                min="1"
                                max="50"
                                value={maxDistance}
                                onChange={(e) => setMaxDistance(Number(e.target.value))}
                                className="w-full mt-2"
                            />
                        </div>
                    </div>
                </div>

                {/* Results */}
                <div className="lg:col-span-3">
                    <div className="mb-4 flex justify-between items-center">
                        <h2 className="text-xl font-semibold text-gray-700">
                            {loading ? 'Buscando...' : `${total} produtos encontrados`}
                        </h2>
                        <div className="text-sm text-gray-500">
                            Ordenado por: <span className="font-medium text-gray-800">Vencimento (mais próximo)</span>
                        </div>
                    </div>

                    {loading ? (
                        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
                            {[...Array(6)].map((_, i) => (
                                <div key={i} className="h-64 bg-gray-100 rounded-lg animate-pulse"></div>
                            ))}
                        </div>
                    ) : (
                        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
                            {products.map((product) => (
                                <ProductCard
                                    key={product.id}
                                    product={product}
                                    onAddToCart={addToCart}
                                />
                            ))}

                            {products.length === 0 && (
                                <div className="col-span-full text-center py-12 bg-white rounded-lg border border-dashed border-gray-300">
                                    <p className="text-gray-500 text-lg">Nenhum produto encontrado nesta região.</p>
                                    <p className="text-gray-400">Tente aumentar o raio de busca ou mudar a localização.</p>
                                </div>
                            )}
                        </div>
                    )}
                </div>
            </div>
        </div>
    )
}

export default ProductSearch
