'use client'

// React Imports
import { useRef, useState } from 'react'
import type { MouseEvent } from 'react'

// Next Imports
import { useParams, useRouter } from 'next/navigation'

// MUI Imports
import { styled } from '@mui/material/styles'
import Badge from '@mui/material/Badge'
import Avatar from '@mui/material/Avatar'
import Popper from '@mui/material/Popper'
import Fade from '@mui/material/Fade'
import Paper from '@mui/material/Paper'
import ClickAwayListener from '@mui/material/ClickAwayListener'
import MenuList from '@mui/material/MenuList'
import Typography from '@mui/material/Typography'
import Divider from '@mui/material/Divider'
import MenuItem from '@mui/material/MenuItem'
import Button from '@mui/material/Button'

// Hook Imports
import { useSettings } from '@core/hooks/useSettings'
import { useAuth } from '@/hooks/useAuth'
import { useTranslations } from 'next-intl'
import useModal from '@/@core/hooks/useModal'
import DialogResetPassword from './resetPassword'
import DialogNewPassword from './newPassword'
import DialogCodeVerfication from './codeverfication'
import { Chip } from '@mui/material'
import { getColorByAccountType } from '@/utils'

// Styled component for badge content
const BadgeContentSpan = styled('span')({
  width: 8,
  height: 8,
  borderRadius: '50%',
  cursor: 'pointer',
  backgroundColor: 'var(--mui-palette-success-main)',
  boxShadow: '0 0 0 2px var(--mui-palette-background-paper)'
})

const UserDropdown = () => {
  // States
  const [openDrop, setOpenDrop] = useState(false)

  // Refs
  const anchorRef = useRef<HTMLDivElement>(null)

  // Hooks
  const router = useRouter()
  const { user, logout, logoutAll } = useAuth()

  const { settings } = useSettings()

  const [openResetModal, setOpenResetModal] = useState<boolean>(false)

  const t = useTranslations('USER_DROPDOWN')

  const handleDropdownOpen = () => {
    !openDrop ? setOpenDrop(true) : setOpenDrop(false)
  }

  const handleDropdownClose = (event?: MouseEvent<HTMLLIElement> | (MouseEvent | TouchEvent), url?: string) => {
    if (url) {
      router.replace(url)
    }

    if (anchorRef.current && anchorRef.current.contains(event?.target as HTMLElement)) {
      return
    }

    setOpenDrop(false)
  }

  const handleUserLogout = async () => {
    logout.mutate(
      {},
      {
        onSuccess: () => {
          handleDropdownClose()
        }
      }
    )
  }

  const handleUserAllLogout = async () => {
    logoutAll.mutate(
      {},
      {
        onSuccess: () => {
          handleDropdownClose()
        }
      }
    )
  }

  const handeleResetPassord = () => {
    setOpenResetModal(!openResetModal)
  }

  return (
    <>
      <Badge
        ref={anchorRef}
        overlap='circular'
        badgeContent={<BadgeContentSpan onClick={handleDropdownOpen} />}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
        className='mis-2'
      >
        <Avatar
          ref={anchorRef}
          alt='John Doe'
          src='/logo.png'
          onClick={handleDropdownOpen}
          className='cursor-pointer bs-[38px] is-[38px]'
        />
      </Badge>
      <Popper
        open={openDrop}
        transition
        disablePortal
        placement='bottom-end'
        anchorEl={anchorRef.current}
        className='min-is-[240px] !mbs-3 z-[1]'
      >
        {({ TransitionProps, placement }) => (
          <Fade
            {...TransitionProps}
            style={{
              transformOrigin: placement === 'bottom-end' ? 'right top' : 'left top'
            }}
          >
            <Paper className={settings.skin === 'bordered' ? 'border shadow-none' : 'shadow-lg'}>
              <ClickAwayListener onClickAway={e => handleDropdownClose(e as MouseEvent | TouchEvent)}>
                <MenuList>
                  <div className='flex items-center plb-2 pli-6 gap-2' tabIndex={-1}>
                    <Avatar alt='John Doe' src='/logo.png' />
                    <div className='flex items-start flex-col'>
                      <Typography className='font-medium' color='text.primary'>
                        {user?.name}
                      </Typography>
                      <Typography variant='caption'>{user?.email}</Typography>
                      <Chip
                        variant='tonal'
                        label={user?.account_type?.replace(/_/g, ' ').replace(/\b\w/g, (l: string) => l.toUpperCase())}
                        size='small'
                        color={getColorByAccountType(user?.account_type || '')}
                        className='capitalize mt-2'
                      />
                    </div>
                  </div>
                  <Divider className='mlb-1' />

                  <MenuItem className='mli-2 gap-3' onClick={handeleResetPassord}>
                    <i className='tabler-lock' />
                    <Typography color='text.primary'>{t('CHANGE-PASSWORD')}</Typography>
                  </MenuItem>
                  <div className='flex items-center flex-col gap-2 plb-2 pli-3'>
                    <Button
                      fullWidth
                      variant='contained'
                      color='error'
                      size='small'
                      endIcon={<i className='tabler-logout' />}
                      onClick={handleUserLogout}
                      sx={{ '& .MuiButton-endIcon': { marginInlineStart: 1.5 } }}
                    >
                      {t('LOGOUT')}
                    </Button>
                    <Button
                      fullWidth
                      variant='contained'
                      color='warning'
                      size='small'
                      endIcon={<i className='tabler-logout' />}
                      onClick={handleUserAllLogout}
                      sx={{ '& .MuiButton-endIcon': { marginInlineStart: 1.5 } }}
                    >
                      {t('LOGOUT_ALL')}
                    </Button>
                  </div>
                </MenuList>
              </ClickAwayListener>
            </Paper>
          </Fade>
        )}
      </Popper>
      <DialogResetPassword
        open={openResetModal}
        handleClose={() => {
          setOpenResetModal(false)
        }}
      />{' '}
      <DialogCodeVerfication />
      <DialogNewPassword />
    </>
  )
}

export default UserDropdown
