import { Col, Container, Row, ScrollView, StyleSystemThemedProps } from 'components/layout';
import {
  Add,
  Dashboard,
  HelpFill,
  SettingsFill,
  AddSquare,
  Edit,
  Chat,
  OpenInWindow,
  BellAlert,
} from 'icons';
import { metrics } from 'config';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useResponsiveLayout, useRouting, useSettings } from 'hooks';
import { COLOR_VALUES } from 'theme/color';
import { useCallback } from 'react';
import { TouchableTile, Button, Text, Visible, Card } from 'components';
import { useReactiveVar } from '@apollo/client';
import { isRoomPageVar } from 'state-management/settings';
import { isNotificationOpenVar, isSettingOpenVar } from 'state-management/dialogs';
import { NavigationRoutes } from 'navigation/enum';
import { Favorite } from './favorite';
import { Header } from './header';

const { STYLES, Z_INDEX } = metrics;

export const SideBar: React.FC<SideBarType> = ({ ...props }) => {
  const { isSideBarOpen, isSideBarCollapsed, setIsSideBarOpen } = useSettings();
  const { isMobile, isTablet, isDesktop } = useResponsiveLayout();
  const { top, bottom } = useSafeAreaInsets();
  const { navigateTo, activeRoute, routeSegments } = useRouting();
  const isRoomPage = useReactiveVar(isRoomPageVar);
  const topMargin = isDesktop ? 0 : top + STYLES.topBarHeight;
  const isDesktopSideNotOpen = isDesktop && !isSideBarOpen;

  const isIndex = routeSegments.includes('inbox');
  const sideBarOpenSide = isMobile ? '100%' : 300;
  const isSideBarOpened = isSideBarOpen ? sideBarOpenSide : 0;
  const isDesktopSideNotOpened = isDesktopSideNotOpen ? STYLES.sideBarWidth : isSideBarOpened;
  const containerWidth = isSideBarCollapsed ? STYLES.sideBarCollapseWidth : isDesktopSideNotOpened;
  const isOverLayVisible = isTablet && isSideBarOpen;

  const alignItems = isSideBarCollapsed ? 'center' : 'stretch';
  const variant = !isSideBarCollapsed && isRoomPage ? 'float' : 'plain';
  const btnSizeVariant = isSideBarCollapsed ? 'undefined' : 'large';
  const isOnMobile = isMobile ? 'xs' : 'xs';
  const marginY = isSideBarCollapsed ? undefined : isOnMobile;

  const flexDirection = isSideBarCollapsed ? 'column-reverse' : 'row';
  const height = isSideBarCollapsed ? 90 : STYLES.bottomBarHeight;

  const helpWidth = isSideBarCollapsed ? 40 : undefined;

  const bottomPL = isSideBarCollapsed ? '2xs' : undefined;
  const mlHelp = isSideBarCollapsed ? undefined : 'xs';

  const isNotificationOpen = useReactiveVar(isNotificationOpenVar);
  const notificationVariant = isNotificationOpen ? 'base' : 'text';

  const spaceBtnVariant = isSideBarCollapsed ? undefined : 'outline';
  const spaceBtnColorVariant = isSideBarCollapsed ? 'transparent' : 'base';

  const getTileVariant = useCallback(
    (route: NavigationRoutes) => {
      const activeRouteColor = route === activeRoute ? 'base' : 'text';
      return isNotificationOpen ? 'text' : activeRouteColor;
    },
    [activeRoute, isNotificationOpen]
  );

  const getIconVariant = useCallback(
    (route: NavigationRoutes) => {
      return route === activeRoute ? 'primary' : 'body';
    },
    [activeRoute]
  );

  const closeSideBar = useCallback(() => {
    setIsSideBarOpen(false);
  }, [setIsSideBarOpen]);

  const openRooms = useCallback(() => {
    navigateTo(NavigationRoutes.Rooms);
    closeSideBar();
  }, [closeSideBar, navigateTo]);

  const openMyRoom = useCallback(() => {
    navigateTo(NavigationRoutes.Rooms);
    closeSideBar();
  }, [closeSideBar, navigateTo]);

  const openDashboard = useCallback(() => {
    navigateTo(NavigationRoutes.Dashboard);
    closeSideBar();
  }, [closeSideBar, navigateTo]);

  const openSettings = useCallback(() => {
    if (isMobile) {
      navigateTo(NavigationRoutes.Settings);
      closeSideBar();
    } else {
      isSettingOpenVar(true);
    }
  }, [closeSideBar, isMobile, navigateTo]);

  const openNotifications = useCallback(() => {
    if (!isIndex) {
      isNotificationOpenVar(true);
    }
  }, [isIndex]);
  const centerElement = useCallback(() => {
    return (
      <>
        <Row>
          <HelpFill colorVariant="body" />
          <Visible if={!isSideBarCollapsed}>
            <Text ml="2xs" variant="body">
              Help & Support
            </Text>
          </Visible>
        </Row>
      </>
    );
  }, [isSideBarCollapsed]);

  return (
    <>
      <Visible if={isOverLayVisible}>
        <Container
          style={{
            position: 'absolute',
            backgroundColor: COLOR_VALUES['underlay-dark'],
            top: topMargin,
            left: 0,
            right: 0,
            bottom: 0,
            zIndex: Z_INDEX.sideBarUnderLay,
          }}
        />
      </Visible>
      <Card
        variant={variant}
        shapeVariant="square"
        flexDirection="column"
        position="absolute"
        top={topMargin}
        paddingBottom={bottom}
        left={0}
        width={containerWidth}
        overflow="hidden"
        right={0}
        bottom={0}
        zIndex={Z_INDEX.sideBar}
        backgroundColor="base-01"
        {...props}
      >
        <Visible if={isDesktop}>
          <Header />
        </Visible>
        <ScrollView>
          <Col px="xs">
            <Col alignItems={alignItems}>
              <Button
                isCollapsed={isSideBarCollapsed}
                my={marginY}
                onPress={() => {}}
                collapsedElement={<AddSquare colorVariant="title" />}
                collapsedWidth={STYLES.sideBarCollapsedItemWidth}
                title="Create new space"
                variant={spaceBtnVariant}
                colorVariant={spaceBtnColorVariant}
                hoverColorVariant="base-02-hover"
                titleVariant="body"
                height={35}
                borderColorVariant="base-02"
                sizeVariant={btnSizeVariant}
                px="xs"
                titleColor="body"
                leftElement={<Add />}
              />
              <TouchableTile
                isCollapsed={isSideBarCollapsed}
                onPress={openDashboard}
                collapsedWidth={STYLES.sideBarCollapsedItemWidth}
                variant={getTileVariant(NavigationRoutes.Dashboard)}
                mt="3xs"
                title="Dashboard"
                shapeVariant="round"
                sizeVariant="medium"
                leftElement={
                  <Dashboard colorVariant={getIconVariant(NavigationRoutes.Dashboard)} />
                }
              />
              <Visible if={false}>
                <TouchableTile
                  isCollapsed={isSideBarCollapsed}
                  collapsedWidth={STYLES.sideBarCollapsedItemWidth}
                  underlayColorVariant="base"
                  mt="xs"
                  shapeVariant="round"
                  onPress={openMyRoom}
                  variant={getTileVariant(NavigationRoutes.Room)}
                  title="Notepad"
                  sizeVariant="medium"
                  leftElement={<Edit colorVariant={getIconVariant(NavigationRoutes.Rooms)} />}
                />
              </Visible>

              <TouchableTile
                isCollapsed={isSideBarCollapsed}
                onPress={openRooms}
                collapsedWidth={STYLES.sideBarCollapsedItemWidth}
                variant={getTileVariant(NavigationRoutes.Rooms)}
                mt="3xs"
                title="Rooms"
                shapeVariant="round"
                sizeVariant="medium"
                leftElement={<Chat colorVariant={getIconVariant(NavigationRoutes.Rooms)} />}
              />
              <TouchableTile
                isCollapsed={isSideBarCollapsed}
                onPress={openNotifications}
                collapsedWidth={STYLES.sideBarCollapsedItemWidth}
                variant={notificationVariant}
                mt="3xs"
                title="Notifications"
                shapeVariant="round"
                sizeVariant="medium"
                leftElement={<BellAlert colorVariant="body" />}
                rightElement={<OpenInWindow colorVariant="body" />}
              />
            </Col>
            <Favorite />
          </Col>
        </ScrollView>

        <Container
          flexDirection={flexDirection}
          height={height}
          pr={'2xs'}
          pl={bottomPL}
          py="2xs"
          justifyContent="space-between"
          borderTopWidth={1}
          borderTopColor="divider"
          alignItems={alignItems}
        >
          <TouchableTile
            alignSelf="center"
            onPress={() => {}}
            titleColor="body"
            ml={mlHelp}
            centerElement={centerElement()}
            sizeVariant="medium"
            width={helpWidth}
            variant="text"
          />
          <TouchableTile
            onPress={openSettings}
            alignSelf="center"
            sizeVariant="medium"
            variant="text"
            centerElement={<SettingsFill colorVariant="body" />}
          />
        </Container>
      </Card>
    </>
  );
};

type SideBarType = StyleSystemThemedProps & {};
