'use client'
import { Fragment, useCallback, useEffect, useState } from 'react'

import Link from 'next/link'
import { usePathname } from 'next/navigation'

import { useRecoilState, useRecoilValue } from 'recoil'
import { dimmedStore, sessionStore } from '@/store/commonAtom'

import { useMessage } from '@/hooks/useMessage'
import { logout } from '@/lib/authActions'

import QSelectBox from '@/components/common/select/QSelectBox'

import UserInfoModal from '@/components/myInfo/UserInfoModal'
import { useAxios } from '@/hooks/useAxios'
import { globalLocaleStore } from '@/store/localeAtom'

export const ToggleonMouse = (e, act, target) => {
  const listWrap = e.target.closest(target)
  const ListItem = Array.from(listWrap.childNodes)
  ListItem.forEach((el) => {
    if (act === 'add') {
      el.classList.add('mouse')
    } else {
      el.classList.remove('mouse')
    }
  })
  if (act === 'add') {
    e.target.parentElement.classList.remove('mouse')
  }
}

export default function Header(props) {
  const [userInfoModal, setUserInfoModal] = useState(false)

  const { userSession } = props
  const [sessionState, setSessionState] = useRecoilState(sessionStore)
  const { getMessage } = useMessage()
  const pathName = usePathname()
  // if (pathName.includes('login') || pathName.includes('join')) {
  //   return null
  // }
  const [selected, setSelected] = useState('')

  const dimmedState = useRecoilValue(dimmedStore)
  const isDimmed = dimmedState ? 'opacity-50 bg-black' : ''

  // Link 이동 자동 로그인
  const [globalLocaleState, setGlbalLocaleState] = useRecoilState(globalLocaleStore)
  const { promisePost } = useAxios(globalLocaleState)

  const qOrderUrl = process.env.NEXT_PUBLIC_Q_ORDER_AUTO_LOGIN_URL
  const qMusubiUrl = process.env.NEXT_PUBLIC_Q_MUSUBI_AUTO_LOGIN_URL

  const [SelectOptions, setSelectOptions] = useState(
    userSession.groupId === '60000' ? [{ id: 0, name: 'Q.ORDER', link: `${qOrderUrl}` }] : [{ id: 1, name: 'Q.Musubi', link: `${qMusubiUrl}` }],
  )

  const getAutoLoginParam = async () => {
    await promisePost({ url: '/api/login/v1.0/user/login/autoLoginEncryptData', data: { loginId: userSession.userId } })
      .then((res) => {
        if (res) {
          setSelectOptions(
            userSession.groupId === '60000'
              ? [{ id: 0, name: 'Q.ORDER', link: `${qOrderUrl}?autoLoginParam1=${encodeURIComponent(res.data)}` }]
              : [{ id: 1, name: 'Q.Musubi', link: `${qMusubiUrl}?autoLoginParam1=${encodeURIComponent(res.data)}` }],
          )
          setSelected(
            userSession.groupId === '60000'
              ? { id: 0, name: 'Q.ORDER', link: `${qOrderUrl}?autoLoginParam1=${encodeURIComponent(res.data)}` }
              : { id: 1, name: 'Q.Musubi', link: `${qMusubiUrl}?autoLoginParam1=${encodeURIComponent(res.data)}` },
          )
        }
      })
      .catch((error) => {
        alert(error.response.data.message)
      })
  }

  useEffect(() => {
    getAutoLoginParam()
  }, [userSession])

  const menus = [
    { id: 0, name: 'header.menus.home', url: '/', children: [] },
    {
      id: 1,
      name: 'header.menus.management',
      url: '',
      children: [
        { id: 3, name: 'header.menus.management.stuff', url: '/management/stuff', children: [] },
        { id: 4, name: 'header.menus.management.plan', url: '/floor-plan', children: [] },
      ],
    },
    {
      id: 2,
      name: 'header.menus.community',
      url: '',
      children: [
        { id: 5, name: 'header.menus.community.notice', url: '/community/notice', children: [] },
        { id: 6, name: 'header.menus.community.faq', url: '/community/faq', children: [] },
        { id: 7, name: 'header.menus.community.archive', url: '/community/archive', children: [] },
      ],
    },
  ]

  const syncSession = useCallback(() => {
    setSessionState({ ...userSession })
  })

  useEffect(() => {
    syncSession()
  }, [userSession])

  const onChangeSelect = (option) => {
    setSelected(option)
  }
  const navPage = () => {
    if (selected.link) {
      location.href = selected.link
    }
  }

  const getMenuTemplate = (menus) => {
    return menus.map((menu) => {
      return (
        <li
          key={`${menu.id}`}
          className={'nav-item'}
          onMouseEnter={(e) => ToggleonMouse(e, 'add', 'nav > ul')}
          onMouseLeave={(e) => ToggleonMouse(e, 'remove', 'nav > ul')}
        >
          {menu.children.length === 0 ? (
            <Link key={`${menu.id}`} href={menu.url}>
              {getMessage(menu.name)}
            </Link>
          ) : (
            <Fragment key={`${menu.id}`}>
              <button>{getMessage(menu.name)}</button>
              <ul className="nav-depth2">
                {menu.children.map((m) => {
                  return (
                    <li
                      key={`${m.id}`}
                      className={'nav-depth2-item'}
                      onMouseEnter={(e) => ToggleonMouse(e, 'add', 'li > ul')}
                      onMouseLeave={(e) => ToggleonMouse(e, 'remove', 'li > ul')}
                    >
                      <Link href={m.url}>{getMessage(m.name)}</Link>
                    </li>
                  )
                })}
              </ul>
            </Fragment>
          )}
        </li>
      )
    })
  }

  return (
    !(pathName.includes('login') || pathName.includes('join') || sessionState.pwdInitYn === 'N') && (
      <header className={isDimmed}>
        <div className="header-inner">
          <div className="header-right">
            <h1 className="logo">
              <Link href={'/'}></Link>
            </h1>
            <nav>
              <ul className="nav-list ">{getMenuTemplate(menus)}</ul>
            </nav>
          </div>
          <div className="header-left">
            <div className="profile-box">
              <Link
                href="#"
                onClick={() => {
                  setUserInfoModal(true)
                }}
              >
                <button className="profile">{userSession.userNm}</button>
              </Link>
              {userInfoModal && <UserInfoModal userId={sessionState.userId} userInfoModal={userInfoModal} setUserInfoModal={setUserInfoModal} />}
            </div>
            <div className="sign-out-box">
              <button className="sign-out" onClick={() => logout()}>
                {getMessage('header.logout')}
              </button>
            </div>
            <div className="select-box">
              <QSelectBox options={SelectOptions} onChange={onChangeSelect} />
            </div>
            <div className="btn-wrap">
              <button className="btn-frame small dark" onClick={() => navPage()}>
                {getMessage('header.go')}
              </button>
            </div>
          </div>
        </div>
      </header>
    )
  )
}
