import { ReactNode } from 'react';

import {
  Button,
  Drawer,
  DrawerBody,
  DrawerContent,
  DrawerHeader,
  DrawerOverlay,
  Flex,
  HStack,
  IconButton,
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  Text,
  useDisclosure,
} from '@chakra-ui/react';
import {
  LuAlignJustify,
  LuArrowBigLeft,
  LuArrowUpSquare,
  LuHelpCircle,
  LuHome,
  LuLogIn,
  LuLogOut,
  LuMoon,
  LuPlusCircle,
  LuSettings,
  LuSun,
  LuUserCircle,
} from 'react-icons/lu';
import { useNavigate } from 'react-router-dom';

import { useServiceContext } from '@/service/ServiceContext';
import { SessionState } from '@/service/SessionState';
import { colors } from '@/theme/foundations/colors';
import { requestSignIn, requestSignOut, requestSignUp } from '@/utils/sso';
import { useThemeMode } from '@/utils/theme-tools';
import { useSessionService } from '@/service/session';

export const TOP_BAR_HEIGHT = '50px';

export const BUTTON_TOP_BAR_PROPERTY = {
  variant: '@menu',
  height: TOP_BAR_HEIGHT,
};

export type TopBarProps = {
  children?: ReactNode;
  title?: string;
};

export const TopBar = ({ title, children }: TopBarProps) => {
  const { mode, colorMode, toggleColorMode } = useThemeMode();
  const { clearToken } = useSessionService();

  const { session } = useServiceContext();
  const backColor = mode('back.100', 'back.800');
  const drawerDisclose = useDisclosure();
  const onChangeTheme = () => {
    drawerDisclose.onOpen();
  };
  const navigate = useNavigate();
  const onSignIn = (): void => {
    clearToken();
    requestSignIn();
  };
  const onSignUp = (): void => {
    clearToken();
    requestSignUp();
  };
  const onSignOut = (): void => {
    clearToken();
    requestSignOut();
  };
  const onSelectAdd = () => {
    navigate('/add');
  };
  const onSelectHome = () => {
    navigate('/');
  };
  const onHelp = () => {
    navigate('/help');
  };
  const onSettings = () => {
    navigate('/settings');
  };
  return (
    <Flex
      position="absolute"
      top={0}
      left={0}
      right={0}
      height={TOP_BAR_HEIGHT}
      alignItems="center"
      justifyContent="space-between"
      backgroundColor={backColor}
      gap="2"
      px="2"
      boxShadow={'0px 2px 4px ' + colors.back[900]}
      zIndex={200}
    >
      <Button {...BUTTON_TOP_BAR_PROPERTY} onClick={onChangeTheme}>
        <LuAlignJustify />
        <Text paddingLeft="3px" fontWeight="bold">
          Karusic
        </Text>
      </Button>
      {title && (
        <Text
          fontSize="20px"
          fontWeight="bold"
          textTransform="uppercase"
          marginRight="auto"
          userSelect="none"
        >
          {title}
        </Text>
      )}
      {children}
      <Flex right="0">
        {session?.state !== SessionState.CONNECTED && (
          <>
            <Button {...BUTTON_TOP_BAR_PROPERTY} onClick={onSignIn}>
              <LuLogIn />
              <Text paddingLeft="3px" fontWeight="bold">
                Sign-in
              </Text>
            </Button>
            <Button
              {...BUTTON_TOP_BAR_PROPERTY}
              onClick={onSignUp}
              disabled={true}
            >
              <LuPlusCircle />
              <Text paddingLeft="3px" fontWeight="bold">
                Sign-up
              </Text>
            </Button>
          </>
        )}
        {session?.state === SessionState.CONNECTED && (
          <Menu>
            <MenuButton
              as={IconButton}
              aria-label="Options"
              icon={<LuUserCircle />}
              {...BUTTON_TOP_BAR_PROPERTY}
              width={TOP_BAR_HEIGHT}
            />
            <MenuList>
              <MenuItem _hover={{}} color={mode('brand.800', 'brand.200')}>
                Sign in as {session?.login ?? 'Fail'}
              </MenuItem>
              <MenuItem icon={<LuSettings />} onClick={onSettings}>Settings</MenuItem>
              <MenuItem icon={<LuHelpCircle />} onClick={onHelp}>Help</MenuItem>
              <MenuItem icon={<LuLogOut />} onClick={onSignOut}>
                Sign-out
              </MenuItem>
              {colorMode === 'light' ? (
                <MenuItem icon={<LuMoon />} onClick={toggleColorMode}>
                  Set dark mode
                </MenuItem>
              ) : (
                <MenuItem icon={<LuSun />} onClick={toggleColorMode}>
                  Set light mode
                </MenuItem>
              )}
            </MenuList>
          </Menu>
        )}
      </Flex>
      <Drawer
        placement="left"
        onClose={drawerDisclose.onClose}
        isOpen={drawerDisclose.isOpen}
      >
        <DrawerOverlay />
        <DrawerContent>
          <DrawerHeader
            paddingY="auto"
            as="button"
            onClick={drawerDisclose.onClose}
            boxShadow={'0px 2px 4px ' + colors.back[900]}
            backgroundColor={backColor}
            color={mode('brand.900', 'brand.50')}
            textTransform="uppercase"
          >
            <HStack height={TOP_BAR_HEIGHT}>
              <LuArrowBigLeft />
              <Text as="span" paddingLeft="3px">
                Karusic
              </Text>
            </HStack>
          </DrawerHeader>
          <DrawerBody paddingX="0px">
            <Button
              background="#00000000"
              borderRadius="0px"
              onClick={onSelectHome}
              width="full"
            >
              <LuHome />
              <Text paddingLeft="3px" fontWeight="bold" marginRight="auto">
                Home
              </Text>
            </Button>
            <hr />
            <Button
              background="#00000000"
              borderRadius="0px"
              onClick={onSelectAdd}
              width="full"
            >
              <LuArrowUpSquare />
              <Text paddingLeft="3px" fontWeight="bold" marginRight="auto">
                Add Media
              </Text>
            </Button>
          </DrawerBody>
        </DrawerContent>
      </Drawer>
    </Flex>
  );
};
