import React from 'react'
import { useTranslation } from 'react-i18next'
import { NavLink } from 'react-router'
import { useUserActions, useUserInfo } from '@/store/userStore'
import { useRouter } from '@/router/hooks'
// import { useLoginStateContext } from '@/pages/sys/login/providers/LoginStateProvider'
import { Divider, type MenuProps } from 'antd'
import Dropdown, { type DropdownProps } from 'antd/es/dropdown/dropdown'
import { useTheme } from '@/theme/hooks'
import { IconButton } from '@/components/icon'

const nameColorList = ['#71BC78', '#5BB4EB', '#F28CAE', '#ED9848', '#DB93DB']
const randomIndex = Math.floor(Math.random() * 5)

/**
 * Account Dropdown
 */
export default function AccountDropdown() {
  const { replace } = useRouter()
  const { username, phone } = useUserInfo()
  const { logout } = useUserActions()
  // const { backToLogin } = useLoginStateContext()
  const { t } = useTranslation()
  const logoutFn = () => {
    try {
      logout()
      // backToLogin();
    } catch (error) {
      console.log(error)
    } finally {
      replace('/login')
    }
  }
  const {
    themeVars: { colors, borderRadius, shadows }
  } = useTheme()

  const contentStyle: React.CSSProperties = {
    backgroundColor: colors.background.default,
    borderRadius: borderRadius.lg,
    boxShadow: shadows.dropdown
  }

  const menuStyle: React.CSSProperties = {
    boxShadow: 'none'
  }

  const dropdownRender: DropdownProps['dropdownRender'] = (menu) => (
    <div style={contentStyle}>
      <div className='flex flex-col items-start p-4'>
        <div>{username}</div>
        <div className='text-gray'>{phone}</div>
      </div>
      <Divider style={{ margin: 0 }} />
      {React.cloneElement(menu as React.ReactElement, { style: menuStyle })}
    </div>
  )

  const items: MenuProps['items'] = [
    {
      label: <NavLink to='/management/user/profile'>{t('sys.menu.user.profile')}</NavLink>,
      key: '0'
    },
    {
      label: <NavLink to='/management/user/account'>{t('sys.menu.user.account')}</NavLink>,
      key: '1'
    },
    { type: 'divider' },
    {
      label: (
        <button className='font-bold text-warning' type='button'>
          {t('sys.login.logout')}
        </button>
      ),
      key: '2',
      onClick: logoutFn
    }
  ]

  return (
    <Dropdown menu={{ items }} trigger={['click']} dropdownRender={dropdownRender}>
      <IconButton className='h-10 w-10 transform-none px-0 hover:scale-105'>
        <div
          className='inline-block w-[32px] h-[32px] rounded-full text-[#fff] text-center leading-[32px] text-[16px]'
          style={{ backgroundColor: nameColorList[randomIndex] }}>
          <span>{username?.slice(0, 1)?.toUpperCase() || '-'}</span>
        </div>
      </IconButton>
    </Dropdown>
  )
}
