import { type FC } from 'react';
import { useInfiniteQuery } from 'react-query';

import {
  IconCircle1,
  IconCircle2,
  IconCircle3,
  IconCircleCheck,
} from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuUserAvatar from '@material-hu/components/composed-components/UserAvatar';
import HuAccordion from '@material-hu/components/design-system/Accordion';
import CardContainer from '@material-hu/components/design-system/CardContainer';
import HuList from '@material-hu/components/design-system/List';

import useGeneralError from 'src/hooks/useGeneralError';
import { vacationsKeys } from 'src/pages/dashboard/timeOff/queries';
import { getApprovalStepApprovers } from 'src/services/vacations';
import {
  type ApprovalStep,
  type ApprovalStepsType,
  StepStatus,
  VacationStatus,
} from 'src/types/vacations';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getListItemsLength, getNextPage } from 'src/utils/pagination';
import {
  analizeExpanded,
  getCorrectColorStep,
  getCorrectStateInStep,
  getPillStep,
} from 'src/utils/vacations';

import InfiniteList from 'src/components/list/InfiniteList';

import { useCanReviewRequest } from '../../hooks/useCanReviewRequest';

export type ApproversAccordionProps = {
  vacationId: number;
  approvalSteps: ApprovalStepsType;
  step: ApprovalStep;
  isManagerView: boolean;
};

const LIMIT = 50;

const ApproversAccordion: FC<ApproversAccordionProps> = props => {
  const { vacationId, approvalSteps, step, isManagerView } = props;
  const canReview = useCanReviewRequest(step);

  const { t } = useLokaliseTranslation('time_off');
  const showGeneralError = useGeneralError();

  const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } =
    useInfiniteQuery(
      vacationsKeys.approvers(vacationId, step.id),
      ({ pageParam = 1 }) =>
        getApprovalStepApprovers({
          vacationId,
          stepId: step.id,
          page: pageParam,
          limit: LIMIT,
        }),
      {
        getNextPageParam: (_, pages) =>
          getNextPage(getListItemsLength(pages), LIMIT, pages),
        onError: err => {
          showGeneralError(err, t('error_loading_approvers'));
        },
        enabled: !step.approver,
      },
    );

  const correctStatelInStep = getCorrectStateInStep(
    step,
    isManagerView,
    canReview,
  );
  const correctColor = getCorrectColorStep(correctStatelInStep);

  const pill = getPillStep(
    step,
    t(`vacations_status_${correctStatelInStep}`),
    correctColor,
  );
  const results = data?.pages.flatMap(page => page.data.items);

  const getStepName = (position: number) => {
    const stepNumber = position.toString();
    return t(`general:step_positions.step_${stepNumber}`);
  };

  const positionToIcon = {
    1: IconCircle1,
    2: IconCircle2,
    3: IconCircle3,
  };

  const getStepIcon = () => {
    if (correctStatelInStep === VacationStatus.APPROVED) {
      return { Icon: IconCircleCheck };
    }
    return {
      Icon: positionToIcon[step.position as keyof typeof positionToIcon],
    };
  };

  return (
    <HuAccordion
      title={getStepName(step.position)}
      elevation={0}
      sx={{
        backgroundColor: ({ palette }) => palette.new.background.elements.grey,
        overflow: 'hidden',
        '& .MuiStack-root': {
          backgroundColor: ({ palette }) =>
            palette.new.background.elements.grey,
        },
      }}
      defaultExpanded={analizeExpanded(approvalSteps, step)}
      pill={pill}
      avatar={{
        ...getStepIcon(),
        color:
          step.state === StepStatus.WAITING_OTHER_STEP ? 'default' : 'primary',
      }}
      customDetail={
        <>
          <Divider
            sx={{
              mt: 1,
              mb: 2,
              borderColor: ({ palette }) => palette.new.border.neutral.default,
            }}
          />
          <Stack sx={{ gap: 2 }}>
            {!!step.approver && (
              <HuUserAvatar
                user={step.approver}
                profileProps={{
                  redirectToPath: `/profile/${step.approver.id}`,
                  showEmployeeInternalId: true,
                }}
              />
            )}
            {!step.approver && (
              <InfiniteList
                isSuccess={!!results}
                isLoading={isLoading}
                isEmpty={results?.length === 0}
                fetchNextPage={fetchNextPage}
                hasNextPage={hasNextPage}
                isFetchingNextPage={isFetchingNextPage}
              >
                <HuList>
                  {results?.map(user => (
                    <HuUserAvatar
                      key={user.id}
                      user={user}
                      profileProps={{
                        redirectToPath: `/profile/${user.id}`,
                        showEmployeeInternalId: true,
                      }}
                    />
                  ))}
                </HuList>
              </InfiniteList>
            )}
            {!!step.comment && (
              <CardContainer
                fullWidth
                sx={{
                  '& .MuiStack-root': {
                    backgroundColor: theme =>
                      theme.palette.new.background.elements.default,
                  },
                }}
              >
                <Stack>
                  <Typography
                    variant="globalXS"
                    sx={{
                      color: theme => theme.palette.new.text.neutral.lighter,
                    }}
                  >
                    {t('reason')}
                  </Typography>
                  <Typography variant="globalXS">{step.comment}</Typography>
                </Stack>
              </CardContainer>
            )}
          </Stack>
        </>
      }
    />
  );
};

export default ApproversAccordion;
