import {
  type Dispatch,
  type FC,
  Fragment,
  type SetStateAction,
  useState,
} from 'react';
import { useFormContext } from 'react-hook-form';

import { useModal } from '@material-hu/hooks/useModal';
import CheckCircleOutlineIcon from '@material-hu/icons/material/CheckCircleOutline';
import HighlightOffIcon from '@material-hu/icons/material/HighlightOff';
import { IconCheck, IconTrash, IconX } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

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

import {
  invalidateTimeOffNotifications,
  useGetManagerTypes,
  useMassiveApproval,
} from 'src/hooks/queryHooks/vacations';
import { updateRequestsManager } from 'src/pages/dashboard/timeOff/queries';
import {
  VacationActionsSources,
  VacationStatus,
  type Vacations,
} from 'src/types/vacations';
import { useLokaliseTranslation } from 'src/utils/i18n';
import {
  countCouldBeAcceptedRejected,
  countCouldBeCancelled,
  getOptionsSelected,
  isDisabledCheckboxRequest,
} from 'src/utils/vacations';

export type RequestRowHeaderProps = {
  countRequest: number;
  vacationData: Vacations;
  onSetSelectAllRequest: Dispatch<SetStateAction<boolean>>;
};

type MassiveApproval = {
  ids: number[];
  action: VacationStatus;
  count: number;
};

const RequestRowHeader1: FC<RequestRowHeaderProps> = props => {
  const { countRequest, vacationData, onSetSelectAllRequest } = props;

  const [massiveApproval, setMassiveApproval] = useState<MassiveApproval>({
    ids: [],
    action: VacationStatus.APPROVED,
    count: 0,
  });

  const { t } = useLokaliseTranslation('time_off');
  const { watch, handleSubmit, reset } = useFormContext();
  const { isAdmin } = useGetManagerTypes();

  const { requests } = watch();

  const handleOnSuccessAndError = () => {
    closeMassiveApprovalModal();
    updateRequestsManager();
    onSetSelectAllRequest(false);
    invalidateTimeOffNotifications();
    reset();
  };

  const mutation = useMassiveApproval({
    ids: massiveApproval.ids,
    state: massiveApproval.action,
    source: VacationActionsSources.MANAGEMENT_LIST_MASSIVE,
    massiveApprovalCount: massiveApproval.count,
    onSuccess: () => handleOnSuccessAndError(),
    onError: () => handleOnSuccessAndError(),
  });

  const availableRequests = vacationData.filter(
    vc => !isDisabledCheckboxRequest(vc, isAdmin),
  );

  const { selectedCount: selectedRequestsCount } = getOptionsSelected(
    requests,
    availableRequests,
  );

  const countAcceptedRejectd = countCouldBeAcceptedRejected(
    vacationData,
    requests,
  );
  const countCancelled = countCouldBeCancelled(vacationData, requests);

  const handleConfirm = handleSubmit(() => mutation.mutate());

  const {
    modal: massiveApprovalModal,
    showModal: showMassiveApprovalModal,
    closeModal: closeMassiveApprovalModal,
  } = useModal(() => (
    <HuDialog
      primaryButtonProps={{
        children: t('CONFIRM'),
        onClick: handleConfirm,
        loading: mutation.isLoading,
      }}
      secondaryButtonProps={{
        children: t('CANCEL'),
        onClick: () => closeMassiveApprovalModal(),
        disabled: mutation.isLoading,
      }}
      title={t('MASSIVE_APPROVAL_MODAL_TITLE', {
        context: massiveApproval?.action,
      })}
      body={
        <Typography sx={{ display: 'inline-flex', gap: 0.5 }}>
          {t('MASSIVE_APPROVAL_MODAL_BODY')}
          <Typography fontWeight="fontWeightBold">
            {t('TOTAL_REQUESTS', { count: massiveApproval?.count })}
          </Typography>
        </Typography>
      }
      onClose={() => closeMassiveApprovalModal()}
    />
  ));

  const handleOnClick = (
    action: VacationStatus,
    count: number,
    ids: number[],
  ) => {
    showMassiveApprovalModal();
    setMassiveApproval({
      action,
      count,
      ids,
    });
  };

  const availableActions = [
    {
      id: 'approve_reject_request',
      enabled:
        !isAdmin ||
        (isAdmin && countAcceptedRejectd.count === selectedRequestsCount),
      option: (
        <>
          <Button
            variant="tertiary"
            onClick={() =>
              handleOnClick(
                VacationStatus.APPROVED,
                countAcceptedRejectd.count,
                countAcceptedRejectd.ids,
              )
            }
            disabled={mutation.isLoading}
            startIcon={<IconCheck />}
          >
            {t('APPROVE')}
          </Button>
          <Button
            variant="tertiary"
            onClick={() =>
              handleOnClick(
                VacationStatus.REJECTED,
                countAcceptedRejectd.count,
                countAcceptedRejectd.ids,
              )
            }
            disabled={mutation.isLoading}
            startIcon={<IconX />}
          >
            {t('REJECT')}
          </Button>
        </>
      ),
    },
    {
      id: 'cancel_request',
      enabled: isAdmin && countCancelled.count === selectedRequestsCount,
      option: (
        <>
          <Button
            variant="tertiary"
            onClick={() =>
              handleOnClick(
                VacationStatus.CANCELLED,
                countCancelled.count,
                countCancelled.ids,
              )
            }
            disabled={mutation.isLoading}
            startIcon={<IconTrash />}
            sx={{ py: 0 }}
          >
            {t('CANCEL')}
          </Button>
        </>
      ),
    },
    {
      id: 'approve_reject_cancel_request',
      enabled: isAdmin && countAcceptedRejectd.count && countCancelled.count,
      option: (
        <>
          <Button
            color="success"
            size="small"
            variant="secondary"
            onClick={() =>
              handleOnClick(
                VacationStatus.APPROVED,
                countAcceptedRejectd.count,
                countAcceptedRejectd.ids,
              )
            }
            disabled={mutation.isLoading}
            startIcon={<CheckCircleOutlineIcon />}
          >
            {t('APPROVE')}
          </Button>
          <Button
            color="error"
            size="small"
            variant="secondary"
            onClick={() =>
              handleOnClick(
                VacationStatus.REJECTED,
                countAcceptedRejectd.count,
                countAcceptedRejectd.ids,
              )
            }
            disabled={mutation.isLoading}
            startIcon={<HighlightOffIcon />}
          >
            {t('REJECT')}
          </Button>
          <Button
            color="error"
            size="small"
            variant="secondary"
            onClick={() =>
              handleOnClick(
                VacationStatus.CANCELLED,
                countCancelled.count,
                countCancelled.ids,
              )
            }
            disabled={mutation.isLoading}
            startIcon={<HighlightOffIcon />}
          >
            {t('CANCEL')}
          </Button>
        </>
      ),
    },
  ];

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

  return (
    <Stack
      sx={{
        flexDirection: 'row',
        width: '100%',
        justifyContent: 'space-between',
        alignItems: 'center',
        px: 2,
        minHeight: 64,
        backgroundColor: theme => theme.palette.new.background.elements.default,
      }}
    >
      {massiveApprovalModal}
      <>
        <Typography
          sx={{
            mb: 0.5,
            textTransform: 'lowercase',
          }}
        >
          {!selectedRequestsCount
            ? t('total_requests', { count: countRequest })
            : t('requests_selected', {
                count: selectedRequestsCount,
                total: countRequest,
              })}
        </Typography>
        {!!selectedRequestsCount && (
          <Stack sx={{ flexDirection: 'row', gap: 1 }}>
            {availableActionsList.map(({ id, option }) => (
              <Fragment key={id}>{option}</Fragment>
            ))}
          </Stack>
        )}
      </>
    </Stack>
  );
};

export default RequestRowHeader1;
