import { useMemo } from 'react';

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

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

import { useFutureBalancesConformation } from 'src/hooks/queryHooks/vacations';
import useFormatDate from 'src/hooks/useFormatDate';
import { type MeUser } from 'src/types/user';
import {
  type PolicyTypes,
  RequestedDaysErrors,
  WarningsRequestedDays,
} from 'src/types/vacations';
import { useLokaliseTranslation } from 'src/utils/i18n';
import {
  buildCreateRequestValidationAlerts,
  getAmountDaysRequestColor,
  getAmountDaysRequestDescription,
  getAmountDaysRequestTitle,
  resolveRequestBalance,
} from 'src/utils/vacations';

type RequestFooterProps = {
  policyType: PolicyTypes;
  currentBalance: number;
  requestedDays: number;
  amountInMoney: number;
  amountInTime: number;
  errorInAmountPerRequest?: boolean;
  errorsRequestedDays?: Record<string, unknown>;
  warningsRequestedDays: Record<string, unknown>;
  user: MeUser;
  isManagerRequesting: boolean;
  amountDiff?: number;
};

export const CreateRequestFooter = (props: RequestFooterProps) => {
  const {
    policyType,
    currentBalance,
    requestedDays,
    amountInMoney,
    amountInTime,
    errorInAmountPerRequest,
    errorsRequestedDays,
    warningsRequestedDays,
    user,
    isManagerRequesting,
    amountDiff,
  } = props;

  const isEditingRequest = isNumber(amountDiff);

  const { t } = useLokaliseTranslation('time_off');
  const { formatDate } = useFormatDate();

  const warningTitles = Object.keys(warningsRequestedDays);

  const isRequestFromNextCycle = warningTitles.includes(
    WarningsRequestedDays.TIME_OFF_REQUEST_FROM_NEXT_CYCLE,
  );

  const useProjectedNextCycleBalance =
    isRequestFromNextCycle && !policyType.immediateFutureDeduction;

  const alertTitle = getAmountDaysRequestTitle(
    requestedDays,
    policyType,
    amountInMoney,
    amountInTime,
    t,
  );

  const { data: futureBalance } = useFutureBalancesConformation(
    policyType.id,
    user!.id,
    {
      enabled: isRequestFromNextCycle,
    },
  );

  const realBalance = useMemo(
    () =>
      resolveRequestBalance(
        currentBalance,
        isRequestFromNextCycle,
        futureBalance,
      ),
    [currentBalance, isRequestFromNextCycle, futureBalance],
  );

  const alertColor = getAmountDaysRequestColor(
    policyType,
    realBalance,
    isEditingRequest ? amountDiff : requestedDays,
    useProjectedNextCycleBalance,
  );

  const alertDescription = getAmountDaysRequestDescription(
    policyType,
    realBalance,
    isEditingRequest ? amountDiff : requestedDays,
    t,
    user!,
    isRequestFromNextCycle,
    futureBalance,
  );

  const futureRequestError =
    errorsRequestedDays?.[
      RequestedDaysErrors.TIME_OFF_FUTURE_REQUEST_NOT_ALLOWED
    ];

  const validationAlertsToShow = buildCreateRequestValidationAlerts({
    t,
    formatDate,
    requestedDays,
    policyType,
    errorInAmountPerRequest,
    errorsRequestedDays,
    warningsRequestedDays,
    isManagerRequesting,
  });

  return (
    <Stack sx={{ gap: 1 }}>
      {!futureRequestError && (
        <Alert
          severity={alertColor}
          title={alertTitle}
          description={alertDescription}
        />
      )}
      {validationAlertsToShow.map(alert => (
        <Alert
          key={`${alert.severity}-${alert.title}`}
          severity={alert.severity}
          title={alert.title}
          description={alert.description ? alert.description : undefined}
          sx={{
            whiteSpace: 'pre-line',
          }}
        />
      ))}
    </Stack>
  );
};
