import { useEffect, useMemo } from 'react';
import { useQuery } from 'react-query';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';

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

import Tabs from '@material-hu/components/design-system/Tabs';
import Title from '@material-hu/components/design-system/Title';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import {
  getCategorizedHoursRequests,
  getPendingRequestsAmount,
} from 'src/services/timeTracking';
import { TimeTrackingCategorizedHourStatus } from 'src/types/timeTracking';
import { useLokaliseTranslation } from 'src/utils/i18n';

import MainSkeleton from './components/MainSkeleton';
import ApprovalCoachmark from './OvertimeApprovalRequests/components/ApprovalCoachmark';
import { timeTrackingKeys } from './queries';
import { timeTrackingRoutes } from './routes';

const HISTORY_STATUS = [
  TimeTrackingCategorizedHourStatus.APPROVED,
  TimeTrackingCategorizedHourStatus.REJECTED,
  TimeTrackingCategorizedHourStatus.AUTO_APPROVED,
].join() as string;

const TimeTracking = () => {
  const { t } = useLokaliseTranslation([
    'time_tracker',
    'time_tracking_common',
    'approval_requests',
  ]);
  const HuGoThemeProvider = useHuGoTheme();
  const navigate = useNavigate();
  const { pathname } = useLocation();

  const { data: quantityApprovals = 0, isLoading: isLoadingPendingApprovals } =
    useQuery({
      queryKey: timeTrackingKeys.categorizedHoursPending(),
      queryFn: getPendingRequestsAmount,
      select: data => data.data.amount,
    });

  const { data: hasHistoryRecords = false, isLoading: isLoadingHistory } =
    useQuery({
      queryKey: timeTrackingKeys.categorizedHoursRequests({
        status: HISTORY_STATUS,
        page: 1,
        limit: 1,
      }),
      queryFn: () =>
        getCategorizedHoursRequests({
          status: HISTORY_STATUS,
          page: 1,
          limit: 1,
        }),
      select: data => (data.data?.count ?? 0) > 0,
    });

  const isLoadingTabData = isLoadingPendingApprovals || isLoadingHistory;
  const showApprovalsTab = quantityApprovals > 0 || hasHistoryRecords;

  const approvalsText =
    quantityApprovals > 0
      ? t('approval_requests:approvals').concat(` (${quantityApprovals})`)
      : t('approval_requests:approvals');

  const TABS = useMemo(
    () => [
      {
        label: t('general:collaborators'),
        value: timeTrackingRoutes.collaborators(),
      },
      ...(showApprovalsTab
        ? [
            {
              label: approvalsText,
              value: timeTrackingRoutes.overtimeApprovalRequests(),
            },
          ]
        : []),
    ],
    [showApprovalsTab, approvalsText, t],
  );

  const currentTab = TABS.find(tab => tab.value === pathname)?.value;
  useEffect(() => {
    if (
      !isLoadingTabData &&
      pathname === timeTrackingRoutes.overtimeApprovalRequests() &&
      !showApprovalsTab
    ) {
      navigate(timeTrackingRoutes.collaborators(), { replace: true });
    }
  }, [pathname, showApprovalsTab, isLoadingTabData, navigate]);

  return (
    <HuGoThemeProvider>
      {showApprovalsTab && <ApprovalCoachmark />}
      <Stack
        sx={{
          backgroundColor: ({ palette }) =>
            palette.new.background.layout.default,
          gap: 4,
          minHeight: '100%',
          pt: 6,
          px: 3,
        }}
      >
        <Title
          variant="L"
          title={t('time_control_title')}
        />
        {isLoadingTabData && <MainSkeleton />}
        {!isLoadingTabData && (
          <>
            <Tabs
              value={currentTab || TABS[0].value}
              onTabChange={tab => {
                navigate(tab);
              }}
              tabs={TABS}
            />
            <Outlet />
          </>
        )}
      </Stack>
    </HuGoThemeProvider>
  );
};

export default TimeTracking;
