import { Button, Dropdown, DropdownItem, DropdownMenu, DropdownTrigger, Tooltip } from '@nextui-org/react'
import { useNavigate } from 'react-router-dom'
import { useSessionStorageState, useTimeout } from 'ahooks'
import { useEffect, useState } from 'react'
import { withAuth } from '@/auth/withAuth'
import type { WithAuthProps } from '@/auth/withAuth'
import UserIcon from '@/assets/svg/user.svg?react'
import { useAuth } from '@/auth/AuthContext'
import { isMobile } from '@/utils'

interface UserProps {
  onLogout: () => void
}

export const UserLogin: React.FC<UserProps> = ({ onLogout }) => {
  const { logout } = useAuth()
  const navigate = useNavigate()

  const items = [
    {
      key: 'protocol02',
      label: '隐私政策',
    },
    {
      key: 'protocol01',
      label: '服务协议',
    },
    {
      key: 'logout',
      label: '退出登录',
    },
  ]
  const handleClick = (key: string) => {
    if (key === 'logout') {
      logout()
      onLogout()
    }
    if (key === 'protocol01') {
      navigate('/protocol/01')
    }
    if (key === 'protocol02') {
      navigate('/protocol/02')
    }
  }
  return (
    <Dropdown>
      <DropdownTrigger>
        <Button variant="light" isIconOnly aria-label="Like">
          <UserIcon />
        </Button>
      </DropdownTrigger>
      <DropdownMenu variant="flat" aria-label="Dynamic Actions" items={items}>
        {item => (
          <DropdownItem
            onClick={() => handleClick(item.key)}
            key={item.key}
            color={item.key === 'logout' ? 'danger' : 'primary'}
            className={item.key === 'logout' ? 'text-danger' : ''}
          >
            {item.label}
          </DropdownItem>
        )}
      </DropdownMenu>
    </Dropdown>

  )
}

const UserNotLoginBase: React.FC<WithAuthProps> = ({ showLoginTip, checkAuth }) => {
  const [navBarVisibleLocal] = useSessionStorageState<string | undefined>(
    '__NAV_BAR_VISIBLE_LOCAL__',
    {
      defaultValue: '0',
      listenStorageChange: true,
    },
  )
  const [navBarVisible, setNavBarVisible] = useState(navBarVisibleLocal === '0')
  useEffect(() => {
    if (navBarVisibleLocal === '0') {
      let timer = null as any
      timer = setTimeout(() => {
        setNavBarVisible(true)
        clearTimeout(timer)
        timer = null
      }, 300)
    }
    if (navBarVisibleLocal === '1') {
      setNavBarVisible(false)
    }
  }, [navBarVisibleLocal])

  return (
    <Tooltip isOpen={navBarVisible && showLoginTip && !isMobile()} color="foreground" content="登录体验更多功能" placement="right">
      <Button onClick={checkAuth} variant="light" isIconOnly aria-label="Like">
        <UserIcon />
      </Button>
    </Tooltip>
  )
}
export const UserNotLogin = withAuth(UserNotLoginBase)

export const User: React.FC<UserProps> = ({ onLogout }) => {
  const { isLoggedIn } = useAuth()
  return isLoggedIn ? <UserLogin onLogout={onLogout} /> : <UserNotLogin />
}
