'use client'
import Input from '@/components/Input'
import { FC, useState, useRef, useEffect } from 'react'
import { useProductSearch } from '@/app/products/hooks/useProductsData'
import { useRouter } from 'next/navigation'
import Image from 'next/image'
import { createPortal } from 'react-dom'

const DesktopSearch: FC = () => {
    const [searchQuery, setSearchQuery] = useState('')
    const [isOpen, setIsOpen] = useState(false)
    const [mounted, setMounted] = useState(false)
    const router = useRouter()
    const dropdownRef = useRef<HTMLDivElement>(null)
    const inputRef = useRef<HTMLDivElement>(null)
    const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0, width: 0 })

    const { data: searchResults, isLoading } = useProductSearch(searchQuery)

    useEffect(() => {
        setMounted(true)
    }, [])

    const handleSearch = (value: string) => {
        setSearchQuery(value)
        setIsOpen(value.length > 0)

        if (value.length > 0 && inputRef.current) {
            const rect = inputRef.current.getBoundingClientRect()
            setDropdownPosition({
                top: rect.bottom + window.scrollY,
                left: rect.left + window.scrollX,
                width: rect.width
            })
        }
    }

    const handleProductClick = (url: string) => {
        router.push(url)
        setSearchQuery('')
        setIsOpen(false)
    }

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                if (inputRef.current && !inputRef.current.contains(event.target as Node)) {
                    setIsOpen(false)
                }
            }
        }

        const updatePosition = () => {
            if (isOpen && inputRef.current) {
                const rect = inputRef.current.getBoundingClientRect()
                setDropdownPosition({
                    top: rect.bottom + window.scrollY,
                    left: rect.left + window.scrollX,
                    width: rect.width
                })
            }
        }

        document.addEventListener('mousedown', handleClickOutside)
        window.addEventListener('scroll', updatePosition, true)
        window.addEventListener('resize', updatePosition)

        return () => {
            document.removeEventListener('mousedown', handleClickOutside)
            window.removeEventListener('scroll', updatePosition, true)
            window.removeEventListener('resize', updatePosition)
        }
    }, [isOpen])

    return (
        <>
            <div className='relative w-[300px] lg:w-[500px]' ref={inputRef}>
                <Input
                    className='w-full'
                    variant='search'
                    placeholder='جستجو'
                    value={searchQuery}
                    onChange={(e) => handleSearch(e.target.value)}
                />
            </div>

            {mounted && isOpen && searchQuery.length > 0 && createPortal(
                <div
                    ref={dropdownRef}
                    className='fixed bg-white rounded-xl shadow-lg border border-gray-200 max-h-[400px] overflow-y-auto z-[99999]'
                    style={{
                        top: `${dropdownPosition.top + 8}px`,
                        left: `${dropdownPosition.left}px`,
                        width: `${dropdownPosition.width}px`
                    }}
                >
                    {isLoading ? (
                        <div className='p-4 text-center text-gray-500'>
                            در حال جستجو...
                        </div>
                    ) : searchResults?.results?.products?.length ? (
                        <div className='py-2'>
                            {searchResults.results.products.map((product) => (
                                <div
                                    key={product._id}
                                    onClick={() => handleProductClick(`/product/${product._id}`)}
                                    className='flex items-center gap-3 px-4 py-3 hover:bg-gray-50 cursor-pointer transition-colors'
                                >
                                    <div className='w-[50px] h-[50px] flex-shrink-0'>
                                        <Image
                                            src={product.imagesUrl.cover}
                                            alt={product.title_fa}
                                            width={50}
                                            height={50}
                                            className='rounded-lg object-cover w-full h-full'
                                            unoptimized
                                        />
                                    </div>
                                    <div className='flex-1 min-w-0'>
                                        <h3 className='text-sm font-medium text-gray-900 truncate'>
                                            {product.title_fa}
                                        </h3>
                                        <p className='text-xs text-gray-500 truncate'>
                                            {product.model}
                                        </p>
                                    </div>
                                </div>
                            ))}
                        </div>
                    ) : (
                        <div className='p-4 text-center text-gray-500'>
                            محصولی یافت نشد
                        </div>
                    )}
                </div>,
                document.body
            )}
        </>
    )
}

export default DesktopSearch

