import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import ReactDOMServer from 'react-dom/server';
import { useQueryClient } from 'react-query';

import { select } from 'd3-selection';
import { OrgChart } from 'humand-org-chart';
import {
  IconAddressBook,
  IconArrowsDiagonal,
  IconArrowsDiagonalMinimize2,
  IconDotsVertical,
  IconDownload,
  IconHighlight,
  IconScreenshot,
} from '@material-hu/icons/tabler';
import Backdrop from '@material-hu/mui/Backdrop';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Snackbar from '@material-hu/mui/Snackbar';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';
import useMediaQuery from '@material-hu/mui/useMediaQuery';

import useSnackbar from '@material-hu/components/design-system/Snackbar';

import { BOX_SHADOW_SNACKBAR, NODE_DIMENSIONS } from 'src/constants/orgChart';
import { useAuth } from 'src/contexts/JWTContext';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { useMobileLayout } from 'src/hooks/useMobileLayout';
import useThemeMode from 'src/hooks/useThemeMode';
import CardButton from 'src/pages/dashboard/orgChart/components/buttons/CardButton';
import NavbarButton from 'src/pages/dashboard/orgChart/components/buttons/NavbarButton';
import SiblingsButton from 'src/pages/dashboard/orgChart/components/buttons/SiblingsButton';
import CardContentMenu from 'src/pages/dashboard/orgChart/components/CardContentMenu';
import CustomNodeContent from 'src/pages/dashboard/orgChart/components/CustomNodeContent';
import DownloadDialog from 'src/pages/dashboard/orgChart/components/DownloadDialog';
import HighlightMenu from 'src/pages/dashboard/orgChart/components/HighlightMenu';
import MoreOptionsMenu from 'src/pages/dashboard/orgChart/components/MoreOptionsMenu';
import OrientationDialog from 'src/pages/dashboard/orgChart/components/OrientationDialog';
import SearchBar from 'src/pages/dashboard/orgChart/components/SearchBar';
import SidebarMenu from 'src/pages/dashboard/orgChart/components/SidebarMenu';
import SidebarMenuMobile from 'src/pages/dashboard/orgChart/components/SidebarMenuMobile';
import { useTranslation } from 'src/pages/dashboard/orgChart/i18n';
import { orgChartKeys } from 'src/pages/dashboard/orgChart/queries';
import { getUserSubordinates } from 'src/services/orgChart';
import {
  addAuxClass,
  getNodePosition,
  getRootNode,
  handleNodeExpandCollapse,
  handleUpdateChart,
  highlightCurrentNode,
  showProfilePictures,
} from 'src/utils/orgChart';

import ModuleTabs from 'src/components/dashboard/people/ModuleTabs';

const TAB_VALUE = '1';

const d3 = {
  select,
};

export type OrganizationChartProps = {
  data: any[];
  userId: number;
  isMobile?: boolean;
};

export const OrganizationChart = ({
  data,
  userId,
  isMobile: isMobileProp = false,
}: OrganizationChartProps) => {
  const d3Container = useRef(null);
  const chartRef = useRef<any>(null);
  if (!chartRef.current) chartRef.current = new OrgChart();
  const chart = chartRef.current;

  useMobileLayout();

  const { instance } = useAuth();

  const queryClient = useQueryClient();

  const { t } = useTranslation();
  const { enqueueSnackbar } = useSnackbar();

  const theme = useTheme();
  const HuGoThemeProvider = useHuGoTheme();
  const { resolvedMode } = useThemeMode();

  const isMobile = isMobileProp || useMediaQuery(theme.breakpoints.down('sm'));

  const [chartData, setChartData] = useState(data);
  const [openDownloadDialog, setOpenDownloadDialog] = useState(false);
  const [openOrientationDialog, setOpenOrientationDialog] = useState(false);
  const [isFullScreen, setIsFullScreen] = useState(false);
  const [addNodes, setAddNodes] = useState(false);
  const [childrenData, setChildrenData] = useState<any>(null);
  const [downloadLoading, setDownloadLoading] = useState(false);

  const [highlightMenuAnchorEl, setHighlightMenuAnchorEl] =
    useState<EventTarget | null>(null);
  const [cardContentMenuAnchorEl, setCardContentMenuAnchorEl] =
    useState<EventTarget | null>(null);
  const [moreOptionsAnchorEl, setMoreOptionsAnchorEl] =
    useState<EventTarget | null>(null);

  const [highlightedValue, setHighlightedValue] = useState(false);

  const [cardContentValue, setCardContentValue] = useState([
    'email',
    'time',
    'department',
    'position',
  ]);

  const [isDownloadingChart, setIsDownloadingChart] = useState(false);

  const [renderPage, setRenderPage] = useState({});

  const [isLoading, setIsLoading] = useState(false);

  // Global guard in capture phase: stop node click when clicking profile links
  useEffect(() => {
    const stopIfProfileLink = (event: Event) => {
      const target = event.target as Element | null;
      if (!target || typeof target.closest !== 'function') return;

      const anchor = target.closest('a.nodeProfileUrl');
      if (anchor) {
        event.stopPropagation();
      }
    };

    document.addEventListener('click', stopIfProfileLink, { capture: true });

    return () => {
      document.removeEventListener('click', stopIfProfileLink, {
        capture: true,
      });
    };
  }, []);

  const getNodeDimensions = () => {
    const contentCount = cardContentValue.filter(
      value => value !== 'time',
    ).length;

    switch (contentCount) {
      case 0:
        return NODE_DIMENSIONS.small;
      case 1:
      case 2:
        return NODE_DIMENSIONS.medium;
      default:
        return NODE_DIMENSIONS.large;
    }
  };

  const nodeDimensions = getNodeDimensions();

  const getChildrenData = async (parentUserId: number) => {
    if (!isLoading) {
      setIsLoading(true);
      try {
        const oldData = await getUserSubordinates(parentUserId);
        const updatedData = oldData?.data?.map(({ ...rest }) => ({
          parentId: parentUserId,
          ...rest,
        }));
        setChildrenData(updatedData);
      } catch (error) {
        console.error('Error fetching user subordinates:', error);
      } finally {
        setIsLoading(false);
      }
    }
  };

  useEffect(() => {
    setChartData(data);
  }, [data]);

  useEffect(() => {
    const elements = document.querySelectorAll('.aux-class');
    elements.forEach((element: Element) => {
      element.classList.remove('aux-class');
      element.classList.add('svg-chart-container');
    });
    const elementsTest = document.querySelectorAll('.svg-chart-container');
    if (elementsTest.length > 1) {
      elementsTest[1].remove();
    }
    const rootNode = getRootNode(chart);
    if (!rootNode) return;
    chart.layout(rootNode.data.orientation);
    chart.render();
    highlightCurrentNode(rootNode.data.currentNodeId);
  }, [renderPage]);

  const handleCardContentValue = (element: string) => {
    const cardContentAux = [...cardContentValue];
    const index = cardContentAux.indexOf(element);
    if (index !== -1) {
      cardContentAux.splice(index, 1);
    } else {
      cardContentAux.push(element);
    }
    setCardContentValue(cardContentAux);
  };

  useEffect(() => {
    handleCenterMarkNode();
    setRenderPage({});
    return () => {
      queryClient.removeQueries(orgChartKeys.allBosses());
      queryClient.removeQueries(orgChartKeys.allSubordinates());
      queryClient.removeQueries(orgChartKeys.Boss());
    };
  }, []);

  const handleBehaviourChange = (changeFunction: Function) => {
    addAuxClass();
    changeFunction();
    setRenderPage({});
  };

  const downloadFeedback = () => {
    enqueueSnackbar({ title: t('DOWNLOAD_SUCCESFULLY'), variant: 'success' });
  };

  const handleHighlightMenuClick = (event: MouseEvent) =>
    handleBehaviourChange(() => setHighlightMenuAnchorEl(event.currentTarget));

  const handleDownloadFeedback = (boolValue: boolean) =>
    handleBehaviourChange(() => setIsDownloadingChart(boolValue));

  const handleCardContentMenuClick = (event: MouseEvent) =>
    handleBehaviourChange(() =>
      setCardContentMenuAnchorEl(event.currentTarget),
    );

  const handleMoreOptionsClick = (event: MouseEvent) =>
    handleBehaviourChange(() => setMoreOptionsAnchorEl(event.currentTarget));

  const handleHighlightMenuClose = () =>
    handleBehaviourChange(() => setHighlightMenuAnchorEl(null));

  const handleCardContentMenuClose = () =>
    handleBehaviourChange(() => setCardContentMenuAnchorEl(null));

  const handleMoreOptionsClose = () =>
    handleBehaviourChange(() => setMoreOptionsAnchorEl(null));

  const handleOpenFullScreen = () =>
    handleBehaviourChange(() => setIsFullScreen(true));

  const handleCloseFullScreen = () =>
    handleBehaviourChange(() => setIsFullScreen(false));

  const handleOpenDownloadDialog = () =>
    handleBehaviourChange(() => setOpenDownloadDialog(true));

  const handleCloseDownloadDialog = () =>
    handleBehaviourChange(() => setOpenDownloadDialog(false));

  const handleOpenOrientationDialog = () => {
    handleMoreOptionsClose();
    addAuxClass();
    setOpenOrientationDialog(true);
    setRenderPage({});
  };

  const handleCloseOrientationDialog = () =>
    handleBehaviourChange(() => setOpenOrientationDialog(false));

  useLayoutEffect(() => {
    let compact = 0;
    if (data && d3Container.current) {
      chart
        .container(d3Container.current)
        .data(chartData)
        .nodeWidth(() => nodeDimensions.width)
        .nodeHeight(() => nodeDimensions.height)
        .compact(!!(compact++ % 2))
        .childrenMargin(() => 100)
        .compactMarginBetween(() => 40)
        .compactMarginPair(() => 80)
        .siblingsMargin(() => 40)
        .setActiveNodeCentered(false)
        .userNode(userId)
        .onShowSiblings((d: any) => {
          chart.clearHighlighting();
          getChildrenData(d.parentId);
        })
        .onNodeClick((d: any) => {
          chart.clearHighlighting();
          const state = chart.getChartState();
          const allNodes = state.allNodes;
          const rootNode = allNodes[0];
          const node = allNodes.find((item: any) => item.data.id === d);
          if (!node) return;
          if (node.data._directSubordinates !== node.data.subordinatesCount) {
            getChildrenData(node.data.id);
          }
          handleNodeExpandCollapse(state, node, rootNode, chart);
          handleUpdateChart(chart, rootNode, node);
          highlightCurrentNode(node.data.id);
          rootNode.data.currentNodeId = node.data.id;
        })
        .nodeContent((node: any, _: any, nodes: any[]): string => {
          return ReactDOMServer.renderToStaticMarkup(
            <CustomNodeContent
              node={node}
              chartColor={nodes[0].__data__.data.chartColor}
              isDarkMode={resolvedMode === 'dark'}
              showDepartment={nodes[0].__data__.data.showDepartment}
              showPosition={nodes[0].__data__.data.showPosition}
              showEmail={nodes[0].__data__.data.showEmail}
              showHireDate={nodes[0].__data__.data.showHireDate}
              instanceColor={instance?.color}
              dimensions={nodeDimensions}
            />,
          );
        })
        .buttonContent(() => {
          return ReactDOMServer.renderToStaticMarkup(
            <div style={{ display: 'none' }} />,
          );
        })
        .nodeUpdate((d: any) => {
          const state = chart.getChartState();
          const orientation = state.layout;
          const { positionX, positionY } = getNodePosition(orientation);
          const allNodes = state.allNodes;
          const parentNode = allNodes.find(
            (node: any) => node.data.id === d.data.parentId,
          );
          const button = d3.select(`#node-button-container-${d.data.id}`);
          const siblingsButtonUpdate = ReactDOMServer.renderToStaticMarkup(
            <SiblingsButton orientation={orientation} />,
          );
          if (
            parentNode &&
            parentNode.data._directSubordinates !==
              parentNode.data.subordinatesCount
          ) {
            button.style('display', 'block');
            button.attr('x', positionX);
            button.attr('y', positionY);
            button.html(siblingsButtonUpdate);
          } else {
            button.style('display', 'none');
          }
        })
        .render();
    }
  }, [renderPage]);

  const handleCenterMarkNode = () => {
    const state = chart.getChartState();
    if (!state?.allNodes) return;
    chart.setCentered(userId);
    chart.setUpToTheRootHighlighted(userId);
    chart.render();
    highlightCurrentNode(userId);
  };

  const handleFitChart = () => {
    const rootNode = getRootNode(chart);
    if (!rootNode) return;
    chart.layout(rootNode.data.orientation);
    chart.render().fit();
    highlightCurrentNode(rootNode.data.currentNodeId);
  };

  const handleFindMe = () => {
    chart.clearHighlighting();
    const rootNode = getRootNode(chart);
    if (!rootNode) return;
    rootNode.data.currentNodeId = userId;
    chart.setUpToTheRootHighlighted(userId);
    chart.layout(rootNode.data.orientation);
    chart.setCentered(userId);
    chart.render();
    highlightCurrentNode(userId);
  };

  const handleFullScreen = () => {
    const dashboardNavbar = document.getElementById('dashboard-navbar');
    const sidebarDrawer = document.getElementById('sidebar-drawer');
    const dashboardLayout = document.getElementById('dashboard-layout-wrapper');

    if (!isFullScreen) {
      if (dashboardNavbar) dashboardNavbar.style.display = 'none';
      if (sidebarDrawer) sidebarDrawer.style.display = 'none';
      if (dashboardLayout) {
        dashboardLayout.style.paddingTop = '0px';
        dashboardLayout.style.paddingLeft = '0px';
      }
      handleOpenFullScreen();
    } else {
      if (dashboardNavbar) dashboardNavbar.style.display = 'block';
      if (sidebarDrawer) sidebarDrawer.style.display = 'block';
      if (dashboardLayout) dashboardLayout.removeAttribute('style');
      handleCloseFullScreen();
    }
  };

  const handleEscKey = (event: KeyboardEvent) => {
    const dashboardNavbar = document.getElementById('dashboard-navbar');
    const sidebarDrawer = document.getElementById('sidebar-drawer');
    const dashboardLayout = document.getElementById('dashboard-layout-wrapper');

    if (event.key === 'Escape' && isFullScreen) {
      if (dashboardNavbar) dashboardNavbar.style.display = 'block';
      if (sidebarDrawer) sidebarDrawer.style.display = 'block';
      if (dashboardLayout) dashboardLayout.removeAttribute('style');
      handleCloseFullScreen();
    }
  };

  useEffect(() => {
    document.addEventListener('keydown', handleEscKey);
    return () => {
      document.removeEventListener('keydown', handleEscKey);
    };
  }, [isFullScreen]);

  const handleChartHighlightValue = (boolValue: boolean) => {
    const rootNode = getRootNode(chart);
    if (!rootNode) return;
    rootNode.data.chartColor = boolValue;
    chart.layout(rootNode.data.orientation);
    chart.render();
    highlightCurrentNode(rootNode.data.currentNodeId);
    addAuxClass();
    setHighlightedValue(boolValue);
    setRenderPage({});
  };

  const handleHighlight = () => {
    const rootNode = getRootNode(chart);
    if (!rootNode) return;
    rootNode.data.chartColor = !rootNode.data.chartColor;
    chart.layout(rootNode.data.orientation);
    chart.render();
    highlightCurrentNode(rootNode.data.currentNodeId);
  };

  const handleSwap = () => {
    const rootNode = getRootNode(chart);
    if (!rootNode) return;
    chart.layout(
      ['right', 'bottom', 'left', 'top'][rootNode.data.orientationIndex % 4],
    );
    rootNode.data.orientation = ['right', 'bottom', 'left', 'top'][
      rootNode.data.orientationIndex % 4
    ];
    rootNode.data.orientationIndex += 1;
    chart.render().fit();
  };

  const handleChartEmailValue = () => {
    const rootNode = getRootNode(chart);
    if (!rootNode) return;
    rootNode.data.showEmail = !rootNode.data.showEmail;
    chart.layout(rootNode.data.orientation);
    chart.render();
    highlightCurrentNode(rootNode.data.currentNodeId);
    addAuxClass();
    handleCardContentValue('email');
    setRenderPage({});
  };

  const handleChartDepartmentValue = () => {
    const rootNode = getRootNode(chart);
    if (!rootNode) return;
    rootNode.data.showDepartment = !rootNode.data.showDepartment;
    chart.layout(rootNode.data.orientation);
    chart.render();
    highlightCurrentNode(rootNode.data.currentNodeId);
    addAuxClass();
    handleCardContentValue('department');
    setRenderPage({});
  };

  const handleChartPositionValue = () => {
    const rootNode = getRootNode(chart);
    if (!rootNode) return;
    rootNode.data.showPosition = !rootNode.data.showPosition;
    chart.layout(rootNode.data.orientation);
    chart.render();
    highlightCurrentNode(rootNode.data.currentNodeId);
    addAuxClass();
    handleCardContentValue('position');
    setRenderPage({});
  };

  const handleChartTimeValue = () => {
    const rootNode = getRootNode(chart);
    if (!rootNode) return;
    rootNode.data.showHireDate = !rootNode.data.showHireDate;
    chart.layout(rootNode.data.orientation);
    chart.render();
    highlightCurrentNode(rootNode.data.currentNodeId);
    addAuxClass();
    handleCardContentValue('time');
    setRenderPage({});
  };

  const handleDownloadScreenshot = () => {
    const rootNode = getRootNode(chart);
    if (!rootNode) return;
    chart.layout(rootNode.data.orientation);
    chart.render();
    highlightCurrentNode(rootNode.data.currentNodeId);
    addAuxClass();
    handleDownloadFeedback(true);

    setTimeout(() => {
      showProfilePictures(false, chart);
      handleDownloadPDF(true);
      setTimeout(() => {
        showProfilePictures(true, chart);
      }, 1000);
    }, 2000);

    setRenderPage({});
  };

  const handleDownloadPDF = (isScreenshot: boolean) => {
    chart.exportImg({
      save: false,
      full: !isScreenshot,
      backgroundColor: '#f4f5f7',
      isPdf: true,
      downloadName: isScreenshot
        ? `${instance?.name ?? ''}-org-chart-screenshot`
        : `${instance?.name ?? ''}-org-chart`,
      onLoad: downloadFeedback,
    });
  };

  const handleDownloadImage = (
    transparentBackground: boolean,
    customBackground: string,
    customBackgroundColor: string,
    isJPG: boolean,
  ) => {
    let backgroundColor = '#f4f5f7';

    if (transparentBackground) {
      backgroundColor = 'transparent';
    } else if (customBackground) {
      backgroundColor = customBackgroundColor;
    }

    chart.exportImg({
      backgroundColor,
      full: true,
      type: isJPG ? 'jpg' : 'png',
      downloadName: `${instance?.name ?? ''}-org-chart`,
      onLoad: downloadFeedback,
    });
  };

  const handleDownloadSvg = () => {
    chart.exportImg({
      full: true,
      isSvg: true,
      downloadName: `${instance?.name ?? ''}-org-chart`,
      onLoad: downloadFeedback,
    });
  };

  const onSubmitOrientation = (orientationData: any) => {
    const rootNode = getRootNode(chart);
    if (!rootNode) return;
    rootNode.data.orientation = orientationData.orientationLayout;
    chart.layout(orientationData.orientationLayout);
    chart.setCentered(rootNode.data.currentNodeId);
    chart.render();
    highlightCurrentNode(rootNode.data.currentNodeId);
    handleCloseOrientationDialog();
  };

  const handleZoomIn = () => {
    const rootNode = getRootNode(chart);
    if (!rootNode) return;
    chart.layout(rootNode.data.orientation);
    chart.zoomIn();
    chart.render();
    highlightCurrentNode(rootNode.data.currentNodeId);
  };

  const handleZoomOut = () => {
    const rootNode = getRootNode(chart);
    if (!rootNode) return;
    chart.layout(rootNode.data.orientation);
    chart.zoomOut();
    chart.render();
    highlightCurrentNode(rootNode.data.currentNodeId);
  };

  const onSubmitDownload = (downloadData: any) => {
    setDownloadLoading(true);

    const rootNode = getRootNode(chart);
    if (!rootNode) return;
    chart.layout(rootNode.data.orientation);
    chart.setCentered(rootNode.data.currentNodeId);
    chart.render().fit();
    highlightCurrentNode(rootNode.data.currentNodeId);
    handleDownloadFeedback(true);

    const downloadFunction = {
      png: (pngData: any) =>
        handleDownloadImage(
          pngData.transparentBackground,
          pngData.customBackground,
          pngData.customColorBackground,
          false,
        ),
      jpg: (jpgData: any) =>
        handleDownloadImage(
          jpgData.transparentBackground,
          jpgData.customBackground,
          jpgData.customColorBackground,
          true,
        ),
      pdf: () => handleDownloadPDF(false),
      svg: () => handleDownloadSvg(),
    };

    setTimeout(() => {
      showProfilePictures(false, chart);
      downloadFunction[
        downloadData.downloadValue as keyof typeof downloadFunction
      ](downloadData);
      setTimeout(() => {
        showProfilePictures(true, chart);
        setDownloadLoading(false);
        handleCloseDownloadDialog();
      }, 1000);
    }, 2000);
  };

  useEffect(() => {
    if (!childrenData?.length) return;
    const state = chart.getChartState();
    const allNodes = state.allNodes;
    const node = allNodes.find(
      (item: any) => item.data.id === childrenData[0].parentId,
    );
    childrenData.forEach((childData: any) => {
      chart.addNode({ ...childData, _expanded: true });
      chart.setExpanded(childData.id, true);
    });
    if (node) node.data._expanded = true;
    chart.data(state.data).render();
  }, [addNodes]);

  useEffect(() => {
    if (!childrenData) return;
    handleBehaviourChange(() => setAddNodes(!addNodes));
  }, [childrenData]);

  return (
    <Stack
      sx={{
        '& .node-rect': {
          stroke: 'none',
        },
      }}
    >
      {!isMobile && (
        <>
          <HuGoThemeProvider>
            <Stack
              sx={{
                width: '100%',
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
                backgroundColor: hugoTheme =>
                  hugoTheme.palette.new.background.layout.default,
                pl: hugoTheme => hugoTheme.spacing(3),
                boxShadow: 'rgb(33 33 33 / 7%) 0px 2px 4px',
                zIndex: 2,
              }}
            >
              <Stack
                sx={{
                  borderBottom: 0,
                  borderColor: 'divider',
                  pt: 2,
                }}
              >
                <ModuleTabs tabValue={TAB_VALUE} />
              </Stack>
              <Stack sx={{ flexDirection: 'row', alignItems: 'center' }}>
                <SearchBar />
                <CardButton
                  title={t('HIGHLIGHTBY')}
                  ElementIcon={<IconHighlight />}
                  handleOnClick={handleHighlightMenuClick}
                />
                <CardButton
                  title={t('CARDCONTENT')}
                  ElementIcon={<IconAddressBook />}
                  handleOnClick={handleCardContentMenuClick}
                />
                <NavbarButton
                  title={t('SCREENSHOT')}
                  ElementIcon={<IconScreenshot />}
                  handleOnClick={handleDownloadScreenshot}
                />
                <NavbarButton
                  title={
                    isFullScreen
                      ? t('general:exit_full_screen')
                      : t('full_screen.title')
                  }
                  ElementIcon={
                    isFullScreen ? (
                      <IconArrowsDiagonalMinimize2 />
                    ) : (
                      <IconArrowsDiagonal />
                    )
                  }
                  handleOnClick={handleFullScreen}
                />
                <NavbarButton
                  title={t('DOWNLOAD')}
                  ElementIcon={<IconDownload />}
                  handleOnClick={handleOpenDownloadDialog}
                />
                <NavbarButton
                  title={t('MORE_OPTIONS')}
                  ElementIcon={<IconDotsVertical />}
                  handleOnClick={handleMoreOptionsClick}
                />
                <CardContentMenu
                  cardContentMenuAnchorEl={cardContentMenuAnchorEl}
                  handleCardContentMenuClose={handleCardContentMenuClose}
                  handleChartEmailValue={handleChartEmailValue}
                  handleChartDepartmentValue={handleChartDepartmentValue}
                  handleChartPositionValue={handleChartPositionValue}
                  handleChartTimeValue={handleChartTimeValue}
                  cardContentValue={cardContentValue}
                />
                <HighlightMenu
                  highlightMenuAnchorEl={highlightMenuAnchorEl}
                  handleHighlightMenuClose={handleHighlightMenuClose}
                  handleChartHighlightValue={handleChartHighlightValue}
                  highlightedValue={highlightedValue}
                />
                <MoreOptionsMenu
                  moreOptionsAnchorEl={moreOptionsAnchorEl}
                  handleMoreOptionsClose={handleMoreOptionsClose}
                  handleOpenOrientationDialog={handleOpenOrientationDialog}
                />
              </Stack>
            </Stack>
          </HuGoThemeProvider>
          {openOrientationDialog && (
            <OrientationDialog
              openOrientationDialog={openOrientationDialog}
              handleCloseOrientationDialog={handleCloseOrientationDialog}
              onOrientationChart={onSubmitOrientation}
            />
          )}
          {openDownloadDialog && (
            <DownloadDialog
              openDownloadDialog={openDownloadDialog}
              handleCloseDownloadDialog={handleCloseDownloadDialog}
              onDownloadChart={onSubmitDownload}
              loading={downloadLoading}
            />
          )}
        </>
      )}
      <Snackbar
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
        open={isDownloadingChart}
        autoHideDuration={2000}
        onClose={() => handleDownloadFeedback(false)}
        message={
          <Typography sx={{ fontSize: '14px', letterSpacing: '0.15px' }}>
            {t('PREPARING_DOWNLOAD')}
          </Typography>
        }
        sx={{
          boxShadow: BOX_SHADOW_SNACKBAR,
          borderRadius: '4px',
          py: 0.5,
          px: 2,
          backgroundColor: '#323232',
          minWidth: '0px',
          '& .MuiPaper-root': {
            minWidth: '0px',
            padding: '0px',
          },
        }}
      />
      {!isMobile && (
        <SidebarMenu
          handleZoomIn={handleZoomIn}
          handleZoomOut={handleZoomOut}
          handleFitChart={handleFitChart}
          handleFindMe={handleFindMe}
        />
      )}
      {isMobile && (
        <SidebarMenuMobile
          handleHighlight={handleHighlight}
          handleSwap={handleSwap}
          handleFitChart={handleFitChart}
          handleFindMe={handleFindMe}
        />
      )}
      {isLoading && (
        <Backdrop
          sx={{
            color: '#fff',
            zIndex: theme.zIndex.drawer + 1,
          }}
          open={isLoading}
          invisible={true}
        >
          <CircularProgress
            color="primary"
            sx={{ width: '60px', height: '60px' }}
          />
        </Backdrop>
      )}
      <HuGoThemeProvider>
        <Stack
          sx={{
            '.svg-chart-container': {
              height: () => {
                if (isMobile) return '100vh';
                if (isFullScreen) return 'calc(100vh - 76px)';
                return 'calc(100vh - 64px - 76px)';
              },
              width: '100%',
              backgroundColor: hugoTheme =>
                hugoTheme.palette.new.background.layout.default,
            },
          }}
        >
          <div
            ref={d3Container}
            id="chart-container"
          />
        </Stack>
      </HuGoThemeProvider>
    </Stack>
  );
};

export default OrganizationChart;
