import { Fragment } from 'react';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import {
  IconCheck,
  IconEdit,
  IconTrash,
  IconX,
} from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

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

import { useAuth } from 'src/contexts/JWTContext';
import {
  type ApprovalStepsType,
  type ResponseRequestTimeOff,
  VacationActionsSources,
  VacationStatus,
} from 'src/types/vacations';
import { useLokaliseTranslation } from 'src/utils/i18n';
import {
  getStepToEvaluate,
  updateNotificationsManager,
} from 'src/utils/vacations';

import useEditRequestDrawer from '../Drawers/useEditRequestDrawer';
import useResolutionDrawer from '../shared/useResolutionDrawer';

export type AvailableActionsProps = {
  requestId: number;
  vacationDetail: ResponseRequestTimeOff;
  onClose: () => void;
  successUpdateRequest: () => void;
  approvalSteps: ApprovalStepsType;
  hasEnabledApproveOrRejectRequest: boolean;
  hasEnabledCancelRequest: boolean;
  hasEnabledEditRequest: boolean;
  isManagerView: boolean;
  cancelProps?: {
    backButton?: boolean;
  };
};

const AvailableActions = (props: AvailableActionsProps) => {
  const {
    requestId,
    vacationDetail,
    approvalSteps,
    onClose,
    successUpdateRequest,
    hasEnabledApproveOrRejectRequest,
    hasEnabledCancelRequest,
    hasEnabledEditRequest,
    isManagerView,
    cancelProps,
  } = props;
  const { t } = useLokaliseTranslation('time_off');
  const { user } = useAuth();
  const policyTypeId = vacationDetail?.policyType.id;

  const stepToEvaluate = getStepToEvaluate(approvalSteps);

  const { drawer: editRequestDrawer, showDrawer: showEditRequestDrawer } =
    useDrawerV2(useEditRequestDrawer);

  const handleOnSuccessApproveOrRejectRequest = (state: VacationStatus) => {
    updateNotificationsManager({
      approvalSteps,
      currentPosition: stepToEvaluate?.position,
      user,
      state,
    });
    successUpdateRequest();
  };

  const isSingleApprovalStep = approvalSteps.length === 1;

  const { mutation: approveMutation, drawer: approveDrawer } =
    useResolutionDrawer({
      mutationProps: {
        requestId,
        stepId: stepToEvaluate?.id,
        policyTypeId,
        state: VacationStatus.APPROVED,
        source: VacationActionsSources.MANAGEMENT_DETAIL,
        onSuccess: () =>
          handleOnSuccessApproveOrRejectRequest(VacationStatus.APPROVED),
        onError: onClose,
        isSingleApprovalStep,
      },
      ...cancelProps,
    });

  const { mutation: rejectMutation, drawer: rejectDrawer } =
    useResolutionDrawer({
      mutationProps: {
        requestId,
        stepId: stepToEvaluate?.id,
        policyTypeId,
        state: VacationStatus.REJECTED,
        source: VacationActionsSources.MANAGEMENT_DETAIL,
        onSuccess: () =>
          handleOnSuccessApproveOrRejectRequest(VacationStatus.REJECTED),
        onError: onClose,
        isSingleApprovalStep,
      },
      ...cancelProps,
    });

  const { mutation: cancelMutation, drawer: cancelDrawer } =
    useResolutionDrawer({
      mutationProps: {
        requestId,
        policyTypeId,
        state: VacationStatus.CANCELLED,
        source: isManagerView
          ? VacationActionsSources.MANAGEMENT_DETAIL
          : VacationActionsSources.COLLABORATOR_DETAIL,
        onSuccess: successUpdateRequest,
        onError: onClose,
        isSingleApprovalStep,
      },
      ...cancelProps,
    });

  const approveVacationRequest = () => approveDrawer.showDrawer();
  const rejectVacationRequest = () => rejectDrawer.showDrawer();
  const cancelVacationRequest = () => cancelDrawer.showDrawer();

  const disableMenuOptions =
    rejectMutation.isLoading ||
    approveMutation.isLoading ||
    cancelMutation.isLoading;

  const availableActions = [
    {
      id: 'approve_or_reject_request',
      enabled: hasEnabledApproveOrRejectRequest,
      option: (
        <>
          <Button
            fullWidth
            color="error"
            size="large"
            variant="secondary"
            onClick={rejectVacationRequest}
            disabled={disableMenuOptions}
            startIcon={<IconX />}
          >
            {t('reject')}
          </Button>
          <Button
            fullWidth
            color="success"
            size="large"
            variant="primary"
            onClick={approveVacationRequest}
            disabled={disableMenuOptions}
            startIcon={<IconCheck />}
          >
            {t('approve')}
          </Button>
        </>
      ),
    },
    {
      id: 'cancel_request',
      enabled: hasEnabledCancelRequest,
      option: (
        <Button
          fullWidth
          color="error"
          size="large"
          variant="secondary"
          onClick={cancelVacationRequest}
          disabled={disableMenuOptions}
          startIcon={<IconTrash />}
        >
          {t('cancel')}
        </Button>
      ),
    },
    {
      id: 'edit_request',
      enabled: hasEnabledEditRequest,
      option: (
        <Button
          fullWidth
          color="primary"
          size="large"
          variant="secondary"
          startIcon={<IconEdit />}
          onClick={() => showEditRequestDrawer({ vacationDetail })}
        >
          {t('edit')}
        </Button>
      ),
    },
  ];

  const availableActionsList = availableActions.filter(
    option => option.enabled,
  );

  return (
    <>
      {approveDrawer.drawer}
      {rejectDrawer.drawer}
      {cancelDrawer.drawer}
      {editRequestDrawer}
      <Stack
        gap={1}
        sx={{ width: '100%', flexDirection: 'row' }}
      >
        {availableActionsList.map(({ id, option }) => (
          <Fragment key={id}>{option}</Fragment>
        ))}
      </Stack>
    </>
  );
};

export default AvailableActions;
