import { Helmet } from 'react-helmet-async';
import { useQuery } from 'react-query';
import { useLocation, useNavigate } from 'react-router';

import {
  IconArrowLeft,
  IconChartPie,
  IconCheckbox,
  IconInbox,
  IconWallpaper,
} from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import Grid from '@material-hu/mui/Grid';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuBadge from '@material-hu/components/design-system/Badge';
import HuSpinner from '@material-hu/components/design-system/ProgressIndicators/Spinner';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { getCountForTaskType } from 'src/pages/dashboard/serviceManagement/services';
import {
  ServiceItemTypes,
  TasksType,
} from 'src/pages/dashboard/serviceManagement/types';
import { BubbleCode } from 'src/types/bubbaloo';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import useAgent from '../hooks/useAgent';
import { useBubbalooCounts } from '../hooks/useBubbalooCount';
import { serviceManagementKeys } from '../queries';
import { serviceManagementRoutes } from '../routes';

import Approvals from './Approvals';
import CoordinatorPanel from './CoordinatorPanel';
import Subtasks from './Subtasks';
import Tickets from './Tickets';

const TOOLTIP_DELAY = 200;
const HEADER_HEIGHT = 70;

const AgentWorkspace = () => {
  const { t } = useLokaliseTranslation('service_management');
  const HugoThemeProvider = useHuGoTheme();
  const navigate = useNavigate();
  const location = useLocation();

  const { isLoadingAgent, isCoordinator } = useAgent();

  const handleNavigateBack = () =>
    navigate(serviceManagementRoutes.servicePortal());

  const isCoordinatorPanel =
    location.pathname === serviceManagementRoutes.agentSide.coordinatorPanel();
  const isApprovalPanel =
    location.pathname === serviceManagementRoutes.agentSide.approvals();
  const isTasksPanel =
    location.pathname === serviceManagementRoutes.agentSide.tasks();
  const isAgentPanel = !isCoordinatorPanel && !isApprovalPanel && !isTasksPanel;

  const getTitle = () => {
    if (isCoordinatorPanel) return t('coordinator_panel');
    if (isTasksPanel) return t('subtasks.title');
    if (isApprovalPanel) return t('approvals.title');
    return t('agent_panel');
  };

  const title = getTitle();
  const showCoordinatorPanel = isCoordinatorPanel && isCoordinator;

  const handleNavigateToAgentPanel = () => {
    if (isAgentPanel) return;
    navigate(serviceManagementRoutes.agentWorkspace());
  };

  const handleNavigateToApprovalsPanel = () => {
    if (isApprovalPanel) return;
    navigate(serviceManagementRoutes.agentSide.approvals());
  };

  const handleNavigateToCoordinatorPanel = () => {
    if (isCoordinatorPanel) return;
    navigate(serviceManagementRoutes.agentSide.coordinatorPanel());
  };

  const handleNavigateToTasksPanel = () => {
    if (isTasksPanel) return;
    navigate(serviceManagementRoutes.agentSide.tasks());
  };

  if (isCoordinatorPanel && !isLoadingAgent && !isCoordinator) {
    navigate(serviceManagementRoutes.agentWorkspace());
  }

  const { data: approvalsCount, isLoading: isLoadingApprovalsCount } = useQuery(
    serviceManagementKeys.tasks.count({
      role: TasksType.AGENT,
      type: ServiceItemTypes.APPROVAL,
    }),
    () => getCountForTaskType(TasksType.AGENT, ServiceItemTypes.APPROVAL),
    {
      select: response => response.data.count,
    },
  );

  const { data: subtasksCount, isLoading: isLoadingSubtasksCount } = useQuery(
    serviceManagementKeys.tasks.count({
      role: TasksType.AGENT,
      type: ServiceItemTypes.SUBTASK,
    }),
    () => getCountForTaskType(TasksType.AGENT, ServiceItemTypes.SUBTASK),
    {
      select: response => response.data.count,
    },
  );

  const loading =
    isLoadingAgent || isLoadingApprovalsCount || isLoadingSubtasksCount;

  const showSubtasks = !!subtasksCount && subtasksCount > 0;
  const showApprovals = !!approvalsCount && approvalsCount > 0;

  const [
    { data: agentTasksBubble = 0 },
    { data: agentSubtasksBubble = 0 },
    { data: approvalsBubble = 0 },
  ] = useBubbalooCounts([
    BubbleCode.SM_AGENT_TASKS,
    BubbleCode.SM_AGENT_SUBTASKS,
    BubbleCode.SM_APPROVAL,
  ]);

  return (
    <HugoThemeProvider>
      <Stack
        sx={{
          backgroundColor: ({ palette }) =>
            palette?.new.background.layout.tertiary,
          height: 1,
          overflow: 'hidden',
        }}
      >
        <Helmet>
          <title>{formatTitle(title)}</title>
        </Helmet>
        <Stack
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            width: '100%',
            height: `${HEADER_HEIGHT}px`,
            backgroundColor: ({ palette }) =>
              palette?.new.background.layout.tertiary,
            gap: 1,
            px: 3,
            py: 2,
            position: 'sticky',
            top: 0,
            left: 0,
            zIndex: 1000,
          }}
        >
          <IconButton
            onClick={handleNavigateBack}
            sx={{
              color: ({ palette }) => palette?.new.text.neutral.default,
            }}
          >
            <IconArrowLeft />
          </IconButton>
          <Typography
            variant="globalL"
            fontWeight="fontWeightSemiBold"
          >
            {title}
          </Typography>
        </Stack>
        <Divider />
        {loading && <HuSpinner sx={{ mt: 5 }} />}
        {!loading && (
          <Grid
            container
            sx={{
              display: 'flex',
              height: `calc(100% - ${HEADER_HEIGHT}px)`,
            }}
          >
            <Grid
              item
              sx={{
                width: '72px',
                position: 'sticky',
                top: 0,
                overflow: 'auto',
                height: 1,
                backgroundColor: ({ palette }) =>
                  palette?.new.background.layout.tertiary,
                borderRight: ({ palette }) =>
                  `1px solid ${palette?.new.border.neutral.default}`,
              }}
            >
              <Stack sx={{ gap: 2, p: 2 }}>
                <HuTooltip
                  description={t('requests')}
                  direction="right"
                  delay={TOOLTIP_DELAY}
                >
                  <HuBadge
                    color="primary"
                    badgeContent={agentTasksBubble}
                    invisible={!agentTasksBubble}
                  >
                    <IconButton
                      onClick={handleNavigateToAgentPanel}
                      sx={{
                        color: ({ palette }) =>
                          palette?.new.text.neutral.default,
                        background: isAgentPanel
                          ? ({ palette }) =>
                              palette?.new.background.layout.default
                          : ({ palette }) =>
                              palette?.new.background.layout.tertiary,
                      }}
                    >
                      <IconInbox size={24} />
                    </IconButton>
                  </HuBadge>
                </HuTooltip>
                {showSubtasks && (
                  <HuTooltip
                    description={t('subtasks.title')}
                    direction="right"
                    delay={TOOLTIP_DELAY}
                  >
                    <HuBadge
                      color="primary"
                      badgeContent={agentSubtasksBubble}
                      invisible={!agentSubtasksBubble}
                    >
                      <IconButton
                        onClick={handleNavigateToTasksPanel}
                        sx={{
                          color: ({ palette }) =>
                            palette?.new.text.neutral.default,
                          background: isTasksPanel
                            ? ({ palette }) =>
                                palette?.new.background.layout.default
                            : ({ palette }) =>
                                palette?.new.background.layout.tertiary,
                        }}
                      >
                        <IconWallpaper size={24} />
                      </IconButton>
                    </HuBadge>
                  </HuTooltip>
                )}
                {showApprovals && (
                  <HuTooltip
                    description={t('approvals.title')}
                    direction="right"
                    delay={TOOLTIP_DELAY}
                  >
                    <HuBadge
                      color="primary"
                      badgeContent={approvalsBubble}
                      invisible={!approvalsBubble}
                    >
                      <IconButton
                        onClick={handleNavigateToApprovalsPanel}
                        sx={{
                          color: ({ palette }) =>
                            palette?.new.text.neutral.default,
                          background: isApprovalPanel
                            ? ({ palette }) =>
                                palette?.new.background.layout.default
                            : ({ palette }) =>
                                palette?.new.background.layout.tertiary,
                        }}
                      >
                        <IconCheckbox size={24} />
                      </IconButton>
                    </HuBadge>
                  </HuTooltip>
                )}
                {isCoordinator && (
                  <>
                    <Divider />
                    <HuTooltip
                      description={t('coordinators')}
                      direction="right"
                      delay={TOOLTIP_DELAY}
                    >
                      <IconButton
                        onClick={handleNavigateToCoordinatorPanel}
                        sx={{
                          color: ({ palette }) =>
                            palette?.new.text.neutral.default,
                          background: isCoordinatorPanel
                            ? ({ palette }) =>
                                palette?.new.background.layout.default
                            : ({ palette }) =>
                                palette?.new.background.layout.tertiary,
                        }}
                      >
                        <IconChartPie size={24} />
                      </IconButton>
                    </HuTooltip>
                  </>
                )}
              </Stack>
            </Grid>
            {isAgentPanel && <Tickets />}
            {showCoordinatorPanel && <CoordinatorPanel />}
            {isApprovalPanel && <Approvals />}
            {isTasksPanel && <Subtasks />}
          </Grid>
        )}
      </Stack>
    </HugoThemeProvider>
  );
};

export default AgentWorkspace;
