import React, { useCallback, useEffect } from 'react'
import { useHookstate } from '@hookstate/core'
import { Link as RouteLink, useNavigate, useLocation } from 'react-router-dom'
import {loadedPreferences, loggedInUser, logout} from '../stateManagement/userState'
import {
  Box,
  Button,
  Flex,
  Link,
  HStack,
  Stack,
  useColorModeValue,
  Menu,
  MenuButton,
  Avatar,
  MenuList,
  MenuItem,
  MenuDivider,
  Icon,
  useColorMode,
  Text,
  Center,
  VStack,
  Tooltip,
  Divider,
  Heading,
  Kbd,
  Spacer,
  useDisclosure,
  useMediaQuery,
} from '@chakra-ui/react'
import { AddIcon, HamburgerIcon, Search2Icon, SettingsIcon } from '@chakra-ui/icons'
import SearchModal from './SearchModal'
import { openAndCloseSearchDialogue } from '../stateManagement/loadingState'
import AdminMode from './authComponents/AdminMode'
import MobileBar from './MobileBar'
import FilterBar from './FilterBar'
import { BiFilterAlt } from 'react-icons/bi'
import {MdOutlinePowerSettingsNew} from "react-icons/md";

export default function NavBar() {
  const filterLoadingState = useHookstate(false)
  const userState = useHookstate(loggedInUser)
  const user = userState.get()
  const setSearchModalOpen = useHookstate(openAndCloseSearchDialogue)
  const searchModalOpen = setSearchModalOpen.get()
  const { colorMode, toggleColorMode } = useColorMode()
  const bgHeader = useColorModeValue('gray.100', 'gray.900')
  const bgLink = useColorModeValue('gray.200', 'gray.700')
  const location = useLocation()
  const history = useNavigate()
  const { isOpen: mobileIsOpen, onOpen: mobileOnOpen, onClose: mobileOnClose } = useDisclosure()
  const { isOpen: filterIsOpen, onOpen: filterOnOpen, onClose: filterOnClose } = useDisclosure()
  const btnRef = React.useRef(null)
  const [isSmallerThan768] = useMediaQuery('(max-width: 768px)')

  const handleKeyPress = useCallback((event: any) => {
    if (event.ctrlKey === true && event.key === ',') {
      event.preventDefault()
      setSearchModalOpen.set(true)
    }

    if (event.ctrlKey && event.key === '.' && location.pathname !== '/games') {
      event.preventDefault()
      history('/games')
    }

    if (event.ctrlKey && event.key === '/' && location.pathname !== '/games/create') {
      event.preventDefault()
      history('/games/create')
    }
  }, [setSearchModalOpen, location.pathname, history])

  useEffect(() => {
    document.addEventListener('keydown', handleKeyPress)

    return () => {
      document.removeEventListener('keydown', handleKeyPress)
    }
  }, [handleKeyPress])

  return (
    <>
      {searchModalOpen ? <SearchModal/> : ''}
      <Flex
          zIndex={10000000}
          bg={bgHeader}
          m="0"
          as="header"
          px="2"
          w="100%"
          h={16}
          top={0}
          alignItems={'center'}
          position={loadedPreferences.get().stickyNav ? "fixed" : "relative"}
          justifyContent={'space-between'}
      >
        <HStack spacing={8} alignItems={'center'}>
          <Box as={RouteLink} to="/">
            Game Database
          </Box>
          <HStack
            as={'nav'}
            spacing={4}
            display={{ base: 'none', md: 'flex' }}
          >
            <Link
              px={2}
              py={1}
              rounded={'md'}
              _hover={{
                textDecoration: 'none',
                bg: bgLink,
              }}
              as={RouteLink}
              to="/games">
              Games
            </Link>
            <Link
              px={2}
              py={1}
              rounded={'md'}
              _hover={{
                textDecoration: 'none',
                bg: bgLink,
              }}
              as={RouteLink}
              to="/games/create">
              Create Game
            </Link>
          </HStack>
        </HStack>

        <Spacer/>
        {isSmallerThan768 ?
          <>
            <Button ref={btnRef} onMouseDown={mobileIsOpen ? mobileOnClose : mobileOnOpen}>
              <HamburgerIcon/>
            </Button>
            <MobileBar mobileIsOpen={mobileIsOpen} mobileOnClose={mobileOnClose} btnRef={btnRef} bgLink={bgLink}
                       user={user} colorMode={colorMode} toggleColorMode={toggleColorMode}/>
          </>
          :
          <Stack direction={'row'}>

            { user.role === 'admin' && <AdminMode/>}
            <Tooltip hasArrow mr={'2'} label={'Filters'} aria-label={'Filters'}>
              <Button
                rounded={'full'}
                bg={'transparent'}
                ref={btnRef}
                minW={0}
                onMouseDown={async () => {
                  if (filterIsOpen) {
                    filterLoadingState.set(false)
                    filterOnClose()
                  } else {
                    filterLoadingState.set(true)
                    filterOnOpen()
                  }
              }}>
                <Icon as={BiFilterAlt}/>
              </Button>
            </Tooltip>
            <FilterBar filterIsOpen={filterIsOpen} filterOnClose={filterOnClose} btnRef={btnRef} filterLoadingState={filterLoadingState} />

            <Tooltip hasArrow mr={'2'} label={'Search: ctrl+s'} aria-label={'Search'}>
              <Button
                rounded={'full'}
                onMouseDown={() => {
                  searchModalOpen ? setSearchModalOpen.set(false) : setSearchModalOpen.set(true)
                }}
                bg={'transparent'}
                cursor={'pointer'}
                minW={0}>
                <Search2Icon/>
              </Button>
            </Tooltip>
            <Menu>
              <Tooltip hasArrow mr={'2'} label={'Settings'} aria-label={'Settings'}>
                <MenuButton
                  as={Button}
                  rounded={'full'}
                  variant={'transparent'}
                  cursor={'pointer'}
                  minW={0}>
                  <SettingsIcon/>
                </MenuButton>
              </Tooltip>
              <MenuList alignItems={'center'}>
                <VStack>
                  {/*<Button onMouseDown={toggleColorMode} w={'70%'}>*/}
                  {/*  {colorMode === 'light' ? <MoonIcon/> : <SunIcon/>}*/}
                  {/*  {colorMode === 'light' ?*/}
                  {/*    <Text mt={'1'} ml={'2'}>Dark</Text> :*/}
                  {/*    <Text mt={'1'} ml={'2'}>Light</Text>}*/}
                  {/*</Button>*/}
                  <Button
                    variant={'solid'}
                    colorScheme={'blue'}
                    size={'md'}
                    leftIcon={<AddIcon/>}
                    as={RouteLink}
                    w={'70%'}
                    to="/games/create">
                    <Text mt="1">Create Game</Text>
                  </Button>
                  <Divider/>
                  <Heading as={'h3'} size={'md'}>Keyboard Shortcuts</Heading>
                  <HStack><Text fontSize={'sm'}>Search:</Text><span><Kbd>ctrl</Kbd> + <Kbd>,</Kbd></span></HStack>
                  <HStack><Text fontSize={'sm'}>Games Grid:</Text><span><Kbd>ctrl</Kbd> + <Kbd>.</Kbd></span></HStack>
                  <HStack><Text fontSize={'sm'}>Create
                    Game:</Text><span><Kbd>ctrl</Kbd> + <Kbd>/</Kbd></span></HStack>
                </VStack>
              </MenuList>
            </Menu>
            <Menu>
              <Tooltip hasArrow mr={'2'} label={'User Info and Logout'} aria-label={'User Info'}>
              <MenuButton
                as={Button}
                rounded={'full'}
                variant={'transparent'}
                cursor={'pointer'}
                minW={0}>
                <Avatar size={'sm'} src={user.avatar}/>
              </MenuButton>
              </Tooltip>
              <MenuList alignItems={'center'}>
                <br/>
                <Center>
                  <Avatar
                    size={'2xl'}
                    src={user.avatar}
                  />
                </Center>
                <br/>
                <Center>
                  <p>{user.displayName}</p>
                </Center>
                <br/>
                <MenuDivider/>
                <MenuItem onClick={() => history('/profile')}>Preferences</MenuItem>
                <MenuItem onClick={() => logout()}><Icon as={MdOutlinePowerSettingsNew} mr={'2'}/> <Text
                  mt={'1'}>Logout</Text></MenuItem>
              </MenuList>
            </Menu>
          </Stack>
        }
      </Flex>
    </>
  )
}
