import { FC, useEffect, useState } from 'react'
import Input from '../components/Input'
import { ArrowDown2, CloseCircle, HambergerMenu, Logout, ProfileCircle, SearchNormal, Setting2 } from 'iconsax-react'
import { useTranslation } from 'react-i18next'
import Notifications from '../pages/notification/Notification'
import { useSharedStore } from './store/sharedStore'
import { Popover, PopoverButton, PopoverPanel } from '@headlessui/react'
import { Link, useLocation } from 'react-router-dom'
import { Paths } from '@/utils/Paths'
import SideBarItem from './SideBarItem'
import AvatarImage from '@/assets/images/avatar_image.png'
import { useGetProfile } from '@/pages/profile/hooks/useProfileData'

const Header: FC = () => {

    const [popoverKey, setPopoverKey] = useState(0);
    const { data } = useGetProfile()
    const [search, setSearch] = useState<string>('')
    const [showSearchResults, setShowSearchResults] = useState(false)
    const [inputFocused, setInputFocused] = useState(false)
    const [showMobileSearch, setShowMobileSearch] = useState(false)
    const { pathname } = useLocation()

    const { t } = useTranslation('global')
    const { setOpenSidebar, openSidebar } = useSharedStore()

    const handleSearchChange = (value: string) => {
        setSearch(value)
        if (value) {
            setShowSearchResults(true)
        } else {
            setShowSearchResults(false)
        }
    }

    const handleInputFocus = () => {
        setInputFocused(true)
        if (search) {
            setShowSearchResults(true)
        }
    }

    const handleInputBlur = (e: React.FocusEvent) => {
        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
        }

        setInputFocused(false)
        setTimeout(() => {
            setShowSearchResults(false)
        }, 200)
    }

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

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

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

            if ((searchContainer && searchInput && isClickOutsideDesktopSearch) ||
                (mobileSearchContainer && mobileSearchInput && isClickOutsideMobileSearch)) {
                setShowSearchResults(false)
                setInputFocused(false)
            }
        }

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

    useEffect(() => {
        setPopoverKey((prevKey) => prevKey + 1)
    }, [pathname])

    return (
        <div className='fixed z-1 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'
                    >
                        <div className='p-4 text-center text-sm text-description'>
                            نتیجه‌ای یافت نشد
                        </div>
                    </div>
                )}
            </div>

            {/* Mobile Layout */}
            <div className={`${showMobileSearch ? 'w-full' : ''} items-center`}>
                {!showMobileSearch && (
                    <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-1 bg-white rounded-xl shadow-lg max-h-[calc(100vh-80px)] overflow-y-auto'
                >
                    <div className='p-4 text-center text-sm text-description'>
                        نتیجه‌ای یافت نشد
                    </div>
                </div>
            )}

            <div className={`flex xl:gap-6 gap-4 items-center ${showMobileSearch ? 'hidden xl:flex' : ''}`}>
                {/* Mobile search icon */}
                {!showMobileSearch && (
                    <div onClick={toggleMobileSearch} className='xl:hidden block'>
                        <SearchNormal size={20} color='black' />
                    </div>
                )}

                <Notifications />

                {
                    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?.emailAddress}
                                        </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={Paths.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?.emailAddress}
                                    </div>

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

                                <div className='pb-6 px-6 border-b border-[#EAEDF5]'>

                                    <SideBarItem
                                        icon={<ProfileCircle color={'black'} size={20} />}
                                        title={t('header.profile')}
                                        isActive
                                        link={Paths.profile}
                                        isWithoutLine
                                    />

                                    <SideBarItem
                                        icon={<Setting2 color={'black'} size={20} />}
                                        title={t('header.setting')}
                                        isActive
                                        link={Paths.setting}
                                        isWithoutLine
                                    />
                                </div>

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

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

export default Header