import { useEffect, useState } from 'react';
import { useQuery } from 'react-query';
import { useParams } from 'react-router';

import CircularProgress from '@material-hu/mui/CircularProgress';
import Stack from '@material-hu/mui/Stack';

import { useRequiredAuth } from 'src/contexts/JWTContext';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { useMobileLayout } from 'src/hooks/useMobileLayout';
import { useMobileToken } from 'src/hooks/useMobileToken';
import OrganizationChart from 'src/pages/dashboard/orgChart/OrganizationChart';
import { orgChartKeys } from 'src/pages/dashboard/orgChart/queries';
import {
  getUserBoss,
  getUserBosses,
  getUserSubordinates,
} from 'src/services/orgChart';
import { getProfileById } from 'src/services/users';
import { isVisible } from 'src/utils/instance';
import { formatNodes } from 'src/utils/orgChart';
import { isMobile } from 'src/utils/recognitions';

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

const TAB_VALUE = 1;

type OrgChartProps = {
  isMobile?: boolean;
};

const OrgChart = ({ isMobile: isMobileProp = false }: OrgChartProps) => {
  const { id: userId } = useParams();
  const { user: loggedUser, instance, permissions } = useRequiredAuth();
  const HuGoThemeProvider = useHuGoTheme();

  const { data } = useQuery(
    orgChartKeys.userProfile(userId),
    () => getProfileById(userId!),
    {
      enabled: !!userId,
    },
  );

  const user = userId && userId !== undefined ? data?.data : loggedUser;

  const [bossId, setBossId] = useState<number | undefined>(undefined);

  useMobileToken(true);
  useMobileLayout();

  const { data: userBosses, isLoading: isLoadingBosses } = useQuery(
    orgChartKeys.detailBosses(user?.id),
    () => getUserBosses(user!.id),
    {
      enabled: !!user,
    },
  );

  const { data: userBoss, isLoading: isLoadingBoss } = useQuery(
    orgChartKeys.detailBoss(user?.id),
    () => getUserBoss(user!.id),
    {
      enabled: !!(user && user.id),
    },
  );

  const { data: subordinates, isLoading: isLoadingSubordinates } = useQuery(
    orgChartKeys.detailSubordinates(bossId),
    () => getUserSubordinates(bossId!),
    {
      enabled: !!bossId,
    },
  );

  useEffect(() => {
    if (userBoss && user) {
      if (userBoss.data.items[0]) {
        setBossId(userBoss.data.items[0].id);
      } else {
        setBossId(user.id);
      }
    }
  }, [user, userBoss]);

  useEffect(() => {
    setBossId(undefined);
  }, [userId]);

  const isEmailVisible = isVisible(
    instance.emailInProfileVisibility,
    loggedUser,
    permissions,
  );

  const nodes = formatNodes(
    user,
    userBoss?.data.items[0],
    userBosses?.data ?? [],
    subordinates?.data ?? [],
    instance,
    bossId!,
    isEmailVisible,
  );

  const isLoading = isLoadingBosses || isLoadingSubordinates || isLoadingBoss;

  if (!isLoading && bossId && user) {
    return (
      <OrganizationChart
        data={nodes}
        userId={user.id}
        isMobile={isMobileProp || isMobile()}
      />
    );
  }

  return (
    <HuGoThemeProvider>
      <Stack
        sx={{
          width: '100%',
          backgroundColor: theme => theme.palette.new.background.layout.default,
          pl: 3,
          zIndex: 2,
          pt: 2,
        }}
      >
        <ModuleTabs tabValue={TAB_VALUE} />
      </Stack>
      <Stack
        sx={{
          flexDirection: 'row',
          width: '100%',
          justifyContent: 'center',
          mt: 4,
        }}
      >
        <CircularProgress
          color="primary"
          sx={{
            width: '44px !important',
            height: '44px !important',
          }}
        />
      </Stack>
    </HuGoThemeProvider>
  );
};

export default OrgChart;
