import { FC, useEffect, useState } from 'react'
import Input from '../components/Input'
import { ArrowDown2, CloseCircle, HambergerMenu, Logout, SearchNormal } from 'iconsax-react'
import AvatarImage from '../assets/images/avatar_image.png'
import { useTranslation } from 'react-i18next'
import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
import { Pages } from '../config/Pages'
import Notifications from '../pages/notification/Notification'
import { useSharedStore } from './store/sharedStore'
import { useGetProfile } from '../pages/profile/hooks/useProfileData'
import { Popover, PopoverButton, PopoverPanel } from '@headlessui/react'
import SideBarItem from './SideBarItem'
import Button from '../components/Button'
import { buildPath } from '../helpers/utils'
import { getToken } from '../config/func'
import { useSearchCompany } from '../pages/home/hooks/useHomeData'
const Header: FC = () => {

    const { isLogin, setIsLogin } = useSharedStore()
    const [search, setSearch] = useState<string>('')
    const { data: searchData, isLoading: searchLoading } = useSearchCompany(search)
    const [showSearchResults, setShowSearchResults] = useState(false)
    const [inputFocused, setInputFocused] = useState(false)
    const [showMobileSearch, setShowMobileSearch] = useState(false)

    const checkLogin = async () => {
        const token = await getToken()
        setIsLogin(!!token)
    }

    const { slug } = useParams()
    const navigate = useNavigate()
    const location = useLocation();
    const [popoverKey, setPopoverKey] = useState(0);
    const { t } = useTranslation('global')
    const { setOpenSidebar, openSidebar } = useSharedStore()
    const { data } = useGetProfile(isLogin ? true : false)


    const handleSearchChange = (value: string) => {
        setSearch(value)
        // Show results if there's text
        if (value) {
            setShowSearchResults(true)
        } else {
            setShowSearchResults(false)
        }
    }

    const handleInputFocus = () => {
        setInputFocused(true)
        // Show results if there's text when focused
        if (search) {
            setShowSearchResults(true)
        }
    }

    const handleInputBlur = (e: React.FocusEvent) => {
        // Don't hide if clicking on the dropdown
        const searchContainer = document.getElementById('search-dropdown-container')
        const mobileSearchContainer = document.getElementById('mobile-search-dropdown-container')

        if ((searchContainer && searchContainer.contains(e.relatedTarget as Node)) ||
            (mobileSearchContainer && mobileSearchContainer.contains(e.relatedTarget as Node))) {
            return
        }

        // Otherwise hide and remove focus
        setInputFocused(false)
        setTimeout(() => {
            // Small delay to allow click events to process first
            setShowSearchResults(false)
        }, 200)
    }

    const toggleMobileSearch = () => {
        setShowMobileSearch(prev => !prev)
        if (!showMobileSearch) {
            // When opening search, set focus
            setTimeout(() => {
                const mobileSearchInput = document.getElementById('mobile-search-input')
                if (mobileSearchInput) {
                    (mobileSearchInput as HTMLInputElement).focus()
                    setInputFocused(true)
                }
            }, 100)
        } else {
            // When closing search, clear results
            setSearch('')
            setShowSearchResults(false)
        }
    }

    useEffect(() => {
        setPopoverKey((prevKey) => prevKey + 1);
        const check = async () => {
            await checkLogin()
        }
        check()
    }, [location.pathname]);

    // Close search results when clicking outside
    useEffect(() => {
        const handleClickOutside = (e: MouseEvent) => {
            const searchContainer = document.getElementById('search-dropdown-container')
            const mobileSearchContainer = document.getElementById('mobile-search-dropdown-container')
            const searchInput = document.getElementById('search-input-container')
            const mobileSearchInput = document.getElementById('mobile-search-input-container')

            // Check for both desktop and mobile separately to avoid false negatives
            const isClickOutsideDesktopSearch =
                searchContainer && !searchContainer.contains(e.target as Node) &&
                searchInput && !searchInput.contains(e.target as Node);

            const isClickOutsideMobileSearch =
                mobileSearchContainer && !mobileSearchContainer.contains(e.target as Node) &&
                mobileSearchInput && !mobileSearchInput.contains(e.target as Node);

            // Only proceed if we have proper elements to check and click is outside both
            if ((searchContainer && searchInput && isClickOutsideDesktopSearch) ||
                (mobileSearchContainer && mobileSearchInput && isClickOutsideMobileSearch)) {
                setShowSearchResults(false)
                setInputFocused(false)
            }
        }

        document.addEventListener('mousedown', handleClickOutside)
        return () => {
            document.removeEventListener('mousedown', handleClickOutside)
        }
    }, [])

    return (
        <div className='fixed z-10 right-4 left-4 xl:right-[285px] top-4 xl:h-16 h-12 flex items-center px-6 bg-white justify-between rounded-[32px] xl:w-[calc(100%-305px)]'>
            {/* Desktop Search */}
            <div className='min-w-[270px] hidden xl:block relative'>
                <div id="search-input-container">
                    <Input
                        variant='search'
                        placeholder={t('header.search')}
                        onChangeSearchFinal={handleSearchChange}
                        onFocus={handleInputFocus}
                        onBlur={handleInputBlur}
                    />
                </div>

                {showSearchResults && search && inputFocused && (
                    <div
                        id="search-dropdown-container"
                        className='absolute z-20 mt-1 w-full bg-white rounded-xl shadow-lg max-h-80 overflow-y-auto'
                    >
                        {searchLoading && (
                            <div className='p-4 text-center text-sm text-description'>
                                در حال جستجو...
                            </div>
                        )}

                        {!searchLoading && searchData?.data?.length === 0 && (
                            <div className='p-4 text-center text-sm text-description'>
                                نتیجه‌ای یافت نشد
                            </div>
                        )}

                        {!searchLoading && searchData?.data?.length > 0 && (
                            <div className='py-2'>
                                {searchData.data.map((company: any) => (
                                    <Link
                                        to={buildPath(`company/${company.id}`, slug)}
                                        key={company.id}
                                        className='flex items-center gap-3 px-4 py-2 hover:bg-gray-50 cursor-pointer'
                                        onClick={() => {
                                            setShowSearchResults(false)
                                            setSearch('')
                                            setInputFocused(false)
                                        }}
                                    >
                                        <div className='w-10 h-10 rounded-full overflow-hidden bg-gray-100'>
                                            {company.profileImageUrl && (
                                                <img
                                                    src={company.profileImageUrl}
                                                    alt={company.name}
                                                    className='w-full h-full object-cover'
                                                />
                                            )}
                                        </div>
                                        <div className='flex flex-col'>
                                            <span className='text-sm font-medium'>{company.name}</span>
                                            <span className='text-xs text-description'>{company.chiefExecutiveOfficer}</span>
                                        </div>
                                    </Link>
                                ))}
                            </div>
                        )}
                    </div>
                )}
            </div>

            {/* Mobile Layout - Only hamburger menu now */}
            <div className={`${showMobileSearch ? 'w-full' : ''} items-center`}>
                {!showMobileSearch && isLogin && (
                    <div onClick={() => setOpenSidebar(!openSidebar)} className='xl:hidden block'>
                        <HambergerMenu size={24} color='black' />
                    </div>
                )}

                {/* Full width mobile search when active */}
                {showMobileSearch && (
                    <div className='flex w-full items-center gap-2'>
                        <div className='flex-1' id="mobile-search-input-container">
                            <Input
                                id="mobile-search-input"
                                variant='search'
                                placeholder={t('header.search')}
                                onChangeSearchFinal={handleSearchChange}
                                onFocus={handleInputFocus}
                                onBlur={handleInputBlur}
                                autoFocus
                            />
                        </div>
                        <div
                            onClick={toggleMobileSearch}
                            className='p-2 flex-shrink-0 flex items-center justify-center'
                        >
                            <CloseCircle size={20} color='#8C90A3' />
                        </div>
                    </div>
                )}
            </div>

            {/* Mobile Search Results */}
            {showMobileSearch && showSearchResults && search && (
                <div
                    id="mobile-search-dropdown-container"
                    className='fixed right-4 left-4 top-16 z-50 bg-white rounded-xl shadow-lg max-h-[calc(100vh-80px)] overflow-y-auto'
                >
                    {searchLoading && (
                        <div className='p-4 text-center text-sm text-description'>
                            در حال جستجو...
                        </div>
                    )}

                    {!searchLoading && searchData?.data?.length === 0 && (
                        <div className='p-4 text-center text-sm text-description'>
                            نتیجه‌ای یافت نشد
                        </div>
                    )}

                    {!searchLoading && searchData?.data?.length > 0 && (
                        <div className='py-2'>
                            {searchData.data.map((company: any) => (
                                <Link
                                    to={buildPath(`company/${company.id}`, slug)}
                                    key={company.id}
                                    className='flex items-center gap-3 px-4 py-2 hover:bg-gray-50 cursor-pointer'
                                    onClick={() => {
                                        setShowSearchResults(false)
                                        setSearch('')
                                        setInputFocused(false)
                                        setShowMobileSearch(false)
                                    }}
                                >
                                    <div className='w-10 h-10 rounded-full overflow-hidden bg-gray-100'>
                                        {company.profileImageUrl && (
                                            <img
                                                src={company.profileImageUrl}
                                                alt={company.name}
                                                className='w-full h-full object-cover'
                                            />
                                        )}
                                    </div>
                                    <div className='flex flex-col'>
                                        <span className='text-sm font-medium'>{company.name}</span>
                                        <span className='text-xs text-description'>{company.chiefExecutiveOfficer}</span>
                                    </div>
                                </Link>
                            ))}
                        </div>
                    )}
                </div>
            )}

            {/* <img src={LogoImage} className='h-6 xl:hidden block absolute right-0 left-0 mx-auto' /> */}
            <div className={`flex xl:gap-6 gap-4 items-center ${showMobileSearch ? 'hidden xl:flex' : ''}`}>
                {/* Mobile search icon - only visible on mobile when search is not active */}
                {!showMobileSearch && (
                    <div onClick={toggleMobileSearch} className='xl:hidden block'>
                        <SearchNormal size={20} color='black' />
                    </div>
                )}

                {/* Notifications */}
                {
                    isLogin ? (
                        <Notifications />
                    )
                        :
                        <Button
                            label='ورود / ثبت نام'
                            className='w-fit h-7 text-xs px-5'
                            onClick={() => navigate(buildPath('auth/login', slug))}
                        />
                }

                {/* User profile menu */}
                {
                    data && (
                        <Popover className="relative" key={popoverKey}>
                            <PopoverButton >
                                <div className='flex gap-2 items-center mt-2.5'>
                                    <div className='size-6 rounded-full bg-description overflow-hidden'>
                                        <img src={data?.data?.user?.profilePic ? data?.data?.user?.profilePic : AvatarImage} className='size-full object-cover' />
                                    </div>
                                    <div className='xl:flex hidden gap-1 items-center'>
                                        <div className='text-xs'>
                                            {data?.data?.user?.firstName + ' ' + data?.data?.user?.lastName}
                                        </div>
                                        <ArrowDown2 size={14} color='#8C90A3' />
                                    </div>
                                </div>
                            </PopoverButton>

                            <PopoverPanel style={{ minHeight: window.innerWidth < 1140 ? window.innerHeight : undefined }} anchor="bottom" className="flex xl:ml-6 overflow-auto flex-col gap-3 bg-white boxShadow xl:mt-7  z-30 py-4 text-xs rounded-2.5 xl:w-[300px] -mt-[50px] w-full fixed xl:h-fit h-full shadow-md">
                                <div className='absolute xl:hidden top-6 left-6'>
                                    <CloseCircle onClick={() => setPopoverKey((prevKey) => prevKey + 1)} size={20} color='black' />
                                </div>
                                <Link to={Pages.profile} className='flex flex-col gap-2 items-center justify-center border-b border-[#EAEDF5] pb-4'>
                                    <div className='size-14 rounded-full overflow-hidden'>
                                        <img src={data?.data?.user?.profilePic ? data?.data?.user?.profilePic : AvatarImage} className='size-full object-cover' />
                                    </div>

                                    <div>
                                        {data?.data?.user?.firstName + ' ' + data?.data?.user?.lastName}
                                    </div>

                                    <div className='text-description'>
                                        {data?.data?.user?.email}
                                    </div>
                                </Link>

                                <div className='px-6 -mt-[2px]'>
                                    <SideBarItem
                                        icon={<Logout color={'black'} size={20} />}
                                        title={t('sidebar.logout')}
                                        isActive
                                        link={Pages.setting}
                                        isWithoutLine
                                        isLogout
                                    />
                                </div>

                            </PopoverPanel>
                        </Popover>
                    )
                }
            </div>
        </div>
    )
}

export default Header