import { useMemo } from 'react';
import { useQuery } from 'react-query';

import { isNumber } from 'lodash-es';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuUserAvatar from '@material-hu/components/composed-components/UserAvatar';
import Alert from '@material-hu/components/design-system/Alert';
import CardContainer from '@material-hu/components/design-system/CardContainer';

import { useAuth } from 'src/contexts/JWTContext';
import useFormatDate from 'src/hooks/useFormatDate';
import useGeneralError from 'src/hooks/useGeneralError';
import { getApprovalStep } from 'src/services/vacations';
import {
  type ResponseRequestTimeOff,
  UnitVacations,
  VacationStatus,
} from 'src/types/vacations';
import { formatDateInVacations } from 'src/utils/date';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { ellipsisTypographyStyle } from '../../constant';
import { vacationsKeys } from '../../queries';
import { ApprovalSteps, Approvers } from '../requestReport';
import RequestDescription from '../requestReport/RequestDescription';
import RequestDetailUploader from '../requestReport/RequestDetailUploader';
import RequestStatus from '../requestReport/RequestStatus';
import SubstituteApproverDetail from '../requestReport/SubstituteApproverDetail';
import { DateRangeDescription, GenericTitleDescription } from '../shared';

type FullDataRequestProps = {
  vacationDetail: ResponseRequestTimeOff;
  isManagerView: boolean;
  requestId: number;
  open: boolean;
};

const FullDataRequest = ({
  vacationDetail,
  isManagerView,
  requestId,
  open,
}: FullDataRequestProps) => {
  const { t } = useLokaliseTranslation('time_off');
  const { user: loggedUser } = useAuth();
  const showGeneralError = useGeneralError();
  const issuer = vacationDetail.issuer;
  const { formatDate } = useFormatDate();

  const { data: approvalStepsData } = useQuery(
    vacationsKeys.steps(requestId),
    () => getApprovalStep(requestId),
    {
      onError: err => {
        showGeneralError(err, t('ERROR_LOADING_APPROVERS'));
      },
      enabled: open,
    },
  );

  const approvalSteps = approvalStepsData?.data || [];

  const amountRequestedTitle =
    vacationDetail?.amountInMoney > 0
      ? t('request_in_time')
      : t('amount_requested');

  const isEdited = vacationDetail.edited;

  const showResolution = useMemo(() => {
    return (
      vacationDetail.state === VacationStatus.APPROVED ||
      vacationDetail.state === VacationStatus.REJECTED ||
      vacationDetail.state === VacationStatus.CANCELLED
    );
  }, [vacationDetail.state]);

  const resolutionWording = useMemo(() => {
    if (vacationDetail.state === VacationStatus.APPROVED) {
      return t('approved_at');
    }
    if (vacationDetail.state === VacationStatus.REJECTED) {
      return t('rejected_at');
    }
    return t('cancelled_at');
  }, [vacationDetail.state, t]);

  return (
    <Stack sx={{ gap: 2 }}>
      <Stack sx={{ gap: 2 }}>
        {vacationDetail.state === VacationStatus.IN_PROGRESS &&
          approvalSteps?.length > 1 && (
            <ApprovalSteps approvalSteps={approvalSteps} />
          )}
        {isEdited && (
          <Alert
            severity="info"
            title={t('request_edited_by_admin')}
            description={t('request_edited_by_admin_description')}
            hasClose
          />
        )}

        {isManagerView && (
          <CardContainer
            color="grey"
            fullWidth
          >
            <Stack>
              <Typography
                variant="globalXS"
                sx={{
                  color: theme => theme.palette.new.text.neutral.lighter,
                }}
              >
                {t('requested_by')}
              </Typography>
              <HuUserAvatar
                user={issuer!}
                profileProps={{
                  redirectToPath: `/profile/${issuer?.id}`,
                }}
                sx={{
                  '& .MuiListItem-root': {
                    py: 0.5,
                    px: 0,
                  },
                  '& .MuiTypography-root': {
                    ...ellipsisTypographyStyle,
                    maxWidth: 500,
                  },
                }}
              />
            </Stack>
          </CardContainer>
        )}
        <GenericTitleDescription
          title={t('request_type_one')}
          description={vacationDetail?.policyType?.name || t('away')}
        />

        <RequestStatus
          vacationDetail={vacationDetail}
          isManagerView={isManagerView}
        />
        {showResolution && vacationDetail.resolutionDate && (
          <GenericTitleDescription
            title={resolutionWording}
            description={formatDate(
              vacationDetail.resolutionDate,
              'dd/MM/yyyy, HH:mm',
            )}
          />
        )}
        {!!approvalSteps && !!approvalSteps?.length && (
          <Approvers
            isManagerView={isManagerView}
            vacationId={requestId!}
            approvalSteps={approvalSteps}
          />
        )}
      </Stack>
      <GenericTitleDescription
        title={t('requested_on')}
        description={formatDateInVacations({
          date: vacationDetail.createdAt,
          user: loggedUser!,
          type: 'P',
        })}
      />
      {isNumber(vacationDetail.amountInTime) &&
        vacationDetail.amountInTime >= 0 && (
          <GenericTitleDescription
            title={amountRequestedTitle}
            description={t(
              vacationDetail?.policyType.unit === UnitVacations.DAYS
                ? 'total_days'
                : 'hours',
              { count: vacationDetail.amountInTime },
            )}
          />
        )}
      {isManagerView && vacationDetail.amountAvailable !== null && (
        <GenericTitleDescription
          title={t('available_time')}
          description={t(
            vacationDetail?.policyType.unit === UnitVacations.DAYS
              ? 'total_days'
              : 'hours',
            { count: vacationDetail.amountAvailable },
          )}
        />
      )}
      {vacationDetail.from.time && vacationDetail.to.time && (
        <GenericTitleDescription
          title={t('request_period_time')}
          description={`${vacationDetail.from.time.slice(0, 5)} - ${vacationDetail.to.time.slice(0, 5)}`}
        />
      )}
      <DateRangeDescription
        title={t('request_period')}
        from={vacationDetail.from}
        to={vacationDetail.to}
      />
      {vacationDetail.amountInMoney > 0 && (
        <GenericTitleDescription
          title={t('request_in_money')}
          description={t('total_days', {
            count: vacationDetail.amountInMoney,
          })}
        />
      )}
      {!!vacationDetail.description?.length && (
        <RequestDescription description={vacationDetail.description} />
      )}
      {!!vacationDetail.substituteApprover && (
        <SubstituteApproverDetail
          substituteApprover={vacationDetail.substituteApprover}
        />
      )}
      <RequestDetailUploader
        isManagerView={isManagerView}
        requestId={requestId}
        vacationDetail={vacationDetail}
      />
    </Stack>
  );
};

export default FullDataRequest;
