import { useState } from 'react'
import { GroupedProduct, ProductWithDistance } from '../types/product'
import { formatCents } from '../utils/format'
import { useCartStore } from '../stores/cartStore'

interface ProductOffersModalProps {
    group: GroupedProduct
    onClose: () => void
}

export const ProductOffersModal = ({ group, onClose }: ProductOffersModalProps) => {
    const addItem = useCartStore((state) => state.addItem)
    const [quantities, setQuantities] = useState<Record<string, number>>({})

    const getQuantity = (productId: string) => quantities[productId] || 1

    const setQuantity = (productId: string, qty: number) => {
        setQuantities(prev => ({ ...prev, [productId]: Math.max(1, qty) }))
    }

    const handleAddToCart = (product: ProductWithDistance) => {
        const qty = getQuantity(product.id)
        addItem({
            id: product.id,
            name: product.name,
            activeIngredient: product.description,
            lab: '',
            batch: product.batch,
            expiry: product.expires_at,
            vendorId: product.seller_id,
            vendorName: `${product.tenant_city}/${product.tenant_state}`,
            unitPrice: product.price_cents
        }, qty)
    }

    // Sort by price (cheapest first)
    const sortedOffers = [...group.offers].sort((a, b) => a.price_cents - b.price_cents)

    return (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[1000] p-4" onClick={onClose}>
            <div
                className="bg-white rounded-xl shadow-2xl max-w-2xl w-full max-h-[80vh] overflow-hidden"
                onClick={(e) => e.stopPropagation()}
            >
                {/* Header */}
                <div className="bg-gradient-to-r from-blue-600 to-blue-700 text-white p-6">
                    <div className="flex justify-between items-start">
                        <div>
                            <h2 className="text-2xl font-bold">{group.name}</h2>
                            <p className="text-blue-100 mt-1">{group.description}</p>
                        </div>
                        <button
                            onClick={onClose}
                            className="text-white/80 hover:text-white hover:bg-white/20 rounded-full p-2 transition-colors"
                        >
                            <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                            </svg>
                        </button>
                    </div>
                    <div className="mt-4 flex items-center gap-4 text-sm">
                        <span className="bg-white/20 px-3 py-1 rounded-full whitespace-nowrap">
                            {group.offerCount} {group.offerCount === 1 ? 'oferta disponível' : 'ofertas disponíveis'}
                        </span>
                        <span className="bg-green-500 px-3 py-1 rounded-full whitespace-nowrap">
                            A partir de {formatCents(group.minPriceCents)}
                        </span>
                    </div>
                </div>

                {/* Offers List */}
                <div className="overflow-y-auto max-h-[50vh] p-4">
                    <div className="space-y-3">
                        {sortedOffers.map((offer, index) => {
                            const isExpiringSoon = new Date(offer.expires_at).getTime() - Date.now() < 30 * 24 * 60 * 60 * 1000
                            const isCheapest = index === 0
                            const qty = getQuantity(offer.id)
                            const maxQty = offer.stock || 999

                            return (
                                <div
                                    key={offer.id}
                                    className={`border rounded-lg p-4 hover:shadow-md transition-shadow ${isCheapest ? 'border-green-300 bg-green-50' : 'border-gray-200'
                                        }`}
                                >
                                    <div className="flex justify-between items-start gap-4">
                                        <div className="flex-1">
                                            <div className="flex items-center gap-2 mb-2 flex-wrap">
                                                {isCheapest && (
                                                    <span className="bg-green-600 text-white text-xs px-2 py-0.5 rounded font-medium whitespace-nowrap">
                                                        Menor preço
                                                    </span>
                                                )}
                                                {isExpiringSoon && (
                                                    <span className="bg-amber-100 text-amber-800 text-xs px-2 py-0.5 rounded font-medium whitespace-nowrap">
                                                        Vence em breve
                                                    </span>
                                                )}
                                            </div>

                                            <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">
                                                <div className="whitespace-nowrap">
                                                    <span className="text-gray-500">Lote:</span>
                                                    <span className="ml-1 font-mono text-gray-700">{offer.batch}</span>
                                                </div>
                                                <div className="whitespace-nowrap">
                                                    <span className="text-gray-500">Validade:</span>
                                                    <span className={`ml-1 font-medium ${isExpiringSoon ? 'text-amber-600' : 'text-gray-700'}`}>
                                                        {new Date(offer.expires_at).toLocaleDateString()}
                                                    </span>
                                                </div>
                                                <div className="flex items-center text-blue-600 whitespace-nowrap">
                                                    <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                                                    </svg>
                                                    <span>{offer.distance_km} km • {offer.tenant_city}/{offer.tenant_state}</span>
                                                </div>
                                                <div className="whitespace-nowrap">
                                                    <span className="text-gray-500">Estoque:</span>
                                                    <span className="ml-1 font-medium text-gray-700">{offer.stock} un.</span>
                                                </div>
                                            </div>
                                        </div>

                                        <div className="text-right flex flex-col items-end gap-2">
                                            <div className="text-2xl font-bold text-green-600">
                                                {formatCents(offer.price_cents)}
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <div className="flex items-center border rounded-lg overflow-hidden">
                                                    <button
                                                        onClick={() => setQuantity(offer.id, qty - 1)}
                                                        disabled={qty <= 1}
                                                        className="px-2 py-1 bg-gray-100 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 font-bold"
                                                    >
                                                        −
                                                    </button>
                                                    <input
                                                        type="number"
                                                        min="1"
                                                        max={maxQty}
                                                        value={qty}
                                                        onChange={(e) => setQuantity(offer.id, Math.min(maxQty, parseInt(e.target.value) || 1))}
                                                        className="w-12 text-center border-x py-1 text-sm font-medium"
                                                    />
                                                    <button
                                                        onClick={() => setQuantity(offer.id, Math.min(maxQty, qty + 1))}
                                                        disabled={qty >= maxQty}
                                                        className="px-2 py-1 bg-gray-100 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 font-bold"
                                                    >
                                                        +
                                                    </button>
                                                </div>
                                                <button
                                                    onClick={() => handleAddToCart(offer)}
                                                    className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors flex items-center gap-2"
                                                >
                                                    <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" />
                                                    </svg>
                                                    Adicionar
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )
                        })}
                    </div>
                </div>

                {/* Footer */}
                <div className="border-t p-4 bg-gray-50">
                    <button
                        onClick={onClose}
                        className="w-full py-2 text-gray-600 hover:text-gray-800 font-medium"
                    >
                        Fechar
                    </button>
                </div>
            </div>
        </div>
    )
}

