import Dialog from '@material-hu/components/design-system/Dialog';
import useSnackbar from '@material-hu/components/design-system/Snackbar';

import { type PathStatusType } from 'src/pages/dashboard/Learning/Paths/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

type ChangePathStatusModalProps = {
  onClose: () => void;
  pathId: number;
  pathStatus: PathStatusType;
  pathTitle: string;
};

const ChangePathStatusModal = ({
  onClose,
  pathStatus,
  pathTitle,
  pathId,
}: ChangePathStatusModalProps) => {
  const { t } = useLokaliseTranslation('learning');
  const { enqueueSnackbar } = useSnackbar();

  const { mutateAsync: changePathStatus, isLoading: isUpdatingPathStatus } =
    useUpdatePathStatus(pathId);

  const handleChangePathStatus = async () => {
    onClose();

    try {
      await changePathStatus(pathStatus === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE');
      enqueueSnackbar({ title: successTitle, variant: 'success' });
    } catch {
      enqueueSnackbar({
        title: t('path.change_status.error'),
        variant: 'error',
      });
    }
  };

  const successTitle = t(
    pathStatus === 'ACTIVE'
      ? 'path.change_status.deactivate.success'
      : 'path.change_status.activate.success',
  );

  const title = t(
    pathStatus === 'ACTIVE'
      ? 'path.change_status.deactivate.title'
      : 'path.change_status.activate.title',
    { pathTitle: `"${pathTitle}"` },
  );

  const textBody = t(
    pathStatus === 'ACTIVE'
      ? 'path.change_status.deactivate.description'
      : 'path.change_status.activate.description',
  );

  const buttonText = t(
    pathStatus === 'ACTIVE'
      ? 'path.change_status.deactivate.action'
      : 'path.change_status.activate.action',
  );

  return (
    <Dialog
      onClose={onClose}
      title={title}
      textBody={textBody}
      primaryButtonProps={{
        children: buttonText,
        onClick: e => {
          e.stopPropagation();
          handleChangePathStatus();
        },
        loading: isUpdatingPathStatus,
        disabled: isUpdatingPathStatus,
      }}
      secondaryButtonProps={{
        children: t('general:cancel'),
        onClick: e => {
          e.stopPropagation();
          onClose();
        },
        disabled: isUpdatingPathStatus,
      }}
    />
  );
};

export default ChangePathStatusModal;
