import { useState, useEffect, useMemo } from 'react'
import { Shell } from '@/layouts/Shell'
import { productService } from '@/services/productService'
import { LocationPicker } from '@/components/LocationPicker'
import { GroupedProductCard } from '@/components/GroupedProductCard'
import { ProductOffersModal } from '@/components/ProductOffersModal'
import { ProductWithDistance, GroupedProduct } from '@/types/product'
import { useAuth } from '@/context/AuthContext'

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

    // Advanced filters
    const [minPrice, setMinPrice] = useState<number | ''>('')
    const [maxPrice, setMaxPrice] = useState<number | ''>('')
    const [minExpiryDays, setMinExpiryDays] = useState<number>(0)
    const [showAdvancedFilters, setShowAdvancedFilters] = useState(false)
    const [sortBy, setSortBy] = useState<'price' | 'distance' | 'expiry'>('price')

    // Modal state
    const [selectedGroup, setSelectedGroup] = useState<GroupedProduct | null>(null)

    // 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,
                    min_price: minPrice !== '' ? minPrice * 100 : undefined,
                    max_price: maxPrice !== '' ? maxPrice * 100 : undefined,
                    min_expiry_days: minExpiryDays > 0 ? minExpiryDays : undefined,
                    page: 1,
                    page_size: 100,
                })
                const safeProducts = Array.isArray(data.products) ? data.products : []
                setProducts(safeProducts)
                setTotal(typeof data.total === 'number' ? data.total : safeProducts.length)
            } catch (err) {
                console.error('Failed to fetch products', err)
            } finally {
                setLoading(false)
            }
        }

        fetchProducts()
    }, [lat, lng, debouncedSearch, maxDistance, minPrice, maxPrice, minExpiryDays])

    // Filter out products from the logged-in user's pharmacy and group by name
    const groupedProducts = useMemo(() => {
        // Filter out own products using company_id (seller_id === company_id)
        const filteredProducts = products.filter(p => {
            // Exclude products from user's own company
            if (user?.companyId && p.seller_id === user.companyId) {
                return false
            }
            return true
        })

        // Group by name (case-insensitive)
        const groups: Record<string, GroupedProduct> = {}

        for (const product of filteredProducts) {
            const key = product.name.toLowerCase().trim()

            if (!groups[key]) {
                groups[key] = {
                    name: product.name,
                    description: product.description,
                    offers: [],
                    minPriceCents: product.price_cents,
                    offerCount: 0
                }
            }

            groups[key].offers.push(product)
            groups[key].offerCount++
            if (product.price_cents < groups[key].minPriceCents) {
                groups[key].minPriceCents = product.price_cents
            }
        }

        // Sort based on selected option
        const groupsArray = Object.values(groups)

        switch (sortBy) {
            case 'price':
                return groupsArray.sort((a, b) => a.minPriceCents - b.minPriceCents)
            case 'distance':
                return groupsArray.sort((a, b) => {
                    const minDistA = Math.min(...a.offers.map(o => o.distance_km))
                    const minDistB = Math.min(...b.offers.map(o => o.distance_km))
                    return minDistA - minDistB
                })
            case 'expiry':
                return groupsArray.sort((a, b) => {
                    const minExpiryA = Math.min(...a.offers.map(o => new Date(o.expires_at).getTime()))
                    const minExpiryB = Math.min(...b.offers.map(o => new Date(o.expires_at).getTime()))
                    return minExpiryA - minExpiryB
                })
            default:
                return groupsArray
        }
    }, [products, user?.id, sortBy])

    // Calculate total visible offers after filtering
    const visibleOffers = useMemo(() => {
        return groupedProducts.reduce((acc, group) => acc + group.offerCount, 0)
    }, [groupedProducts])

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

    const clearFilters = () => {
        setSearch('')
        setMinPrice('')
        setMaxPrice('')
        setMinExpiryDays(0)
        setMaxDistance(5000)
    }

    return (
        <Shell>
            <div className="container mx-auto">
                <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">
                    <div className="lg:col-span-1 space-y-6">
                        <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 >= 5000 ? 'Nacional' : `${maxDistance} km`}</span>
                                </label>
                                <input
                                    type="range"
                                    min="1"
                                    max="5000"
                                    step="10"
                                    value={maxDistance}
                                    onChange={(e) => setMaxDistance(Number(e.target.value))}
                                    className="w-full mt-2"
                                />
                            </div>

                            {/* Toggle Advanced Filters */}
                            <button
                                type="button"
                                onClick={() => setShowAdvancedFilters(!showAdvancedFilters)}
                                className="text-sm text-blue-600 hover:text-blue-800 flex items-center gap-1"
                            >
                                <svg
                                    xmlns="http://www.w3.org/2000/svg"
                                    className={`h-4 w-4 transition-transform ${showAdvancedFilters ? 'rotate-180' : ''}`}
                                    fill="none"
                                    viewBox="0 0 24 24"
                                    stroke="currentColor"
                                >
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                                </svg>
                                {showAdvancedFilters ? 'Ocultar filtros avançados' : 'Mostrar filtros avançados'}
                            </button>

                            {showAdvancedFilters && (
                                <div className="space-y-4 pt-4 border-t border-gray-200">
                                    <div className="grid grid-cols-2 gap-2">
                                        <div>
                                            <label className="block text-xs font-medium text-gray-700">Preço mín (R$)</label>
                                            <input
                                                type="number"
                                                min="0"
                                                step="0.01"
                                                value={minPrice}
                                                onChange={(e) => setMinPrice(e.target.value ? Number(e.target.value) : '')}
                                                placeholder="0,00"
                                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm sm:text-sm p-2 border"
                                            />
                                        </div>
                                        <div>
                                            <label className="block text-xs font-medium text-gray-700">Preço máx (R$)</label>
                                            <input
                                                type="number"
                                                min="0"
                                                step="0.01"
                                                value={maxPrice}
                                                onChange={(e) => setMaxPrice(e.target.value ? Number(e.target.value) : '')}
                                                placeholder="999,99"
                                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm sm:text-sm p-2 border"
                                            />
                                        </div>
                                    </div>

                                    <div>
                                        <label className="block text-xs font-medium text-gray-700">
                                            Validade mínima: <span className="text-primary font-bold">{minExpiryDays} dias</span>
                                        </label>
                                        <input
                                            type="range"
                                            min="0"
                                            max="365"
                                            step="30"
                                            value={minExpiryDays}
                                            onChange={(e) => setMinExpiryDays(Number(e.target.value))}
                                            className="w-full mt-2"
                                        />
                                        <p className="text-xs text-gray-500 mt-1">
                                            Excluir produtos que vencem antes de {minExpiryDays} dias
                                        </p>
                                    </div>

                                    <button
                                        type="button"
                                        onClick={clearFilters}
                                        className="w-full text-sm text-red-600 hover:text-red-800 py-2 border border-red-200 rounded-md hover:bg-red-50"
                                    >
                                        Limpar todos os filtros
                                    </button>
                                </div>
                            )}
                        </div>

                        <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>

                    {/* 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...' : `${groupedProducts.length} medicamentos (${visibleOffers} ofertas)`}
                            </h2>
                            <div className="flex items-center gap-2 text-sm">
                                <span className="text-gray-500">Ordenar por:</span>
                                <select
                                    value={sortBy}
                                    onChange={(e) => setSortBy(e.target.value as 'price' | 'distance' | 'expiry')}
                                    className="rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary text-sm p-1.5 border bg-white cursor-pointer"
                                >
                                    <option value="price">Menor preço</option>
                                    <option value="distance">Mais próximo</option>
                                    <option value="expiry">Vencimento (mais próximo)</option>
                                </select>
                            </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">
                                {groupedProducts.map((group) => (
                                    <GroupedProductCard
                                        key={group.name}
                                        group={group}
                                        onClick={() => setSelectedGroup(group)}
                                    />
                                ))}

                                {groupedProducts.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>

            {/* Modal */}
            {selectedGroup && (
                <ProductOffersModal
                    group={selectedGroup}
                    onClose={() => setSelectedGroup(null)}
                />
            )}
        </Shell>
    )
}

export default ProductSearch
