import { type MouseEvent } from 'react';

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

import { useLokaliseTranslation } from 'src/utils/i18n';

import { type CategoryItem } from '../../types';
import { hasChildren } from '../../utils';
import useDeleteCategory from '../useDeleteCategory';

type DeleteCategoryModalProps = {
  onClose: () => void;
  onDelete?: () => void;
  category: Omit<CategoryItem, 'id'> & { id?: number };
};

const DeleteCategoryModal = ({
  onClose,
  onDelete,
  category,
}: DeleteCategoryModalProps) => {
  const { t } = useLokaliseTranslation('learning');

  const { mutate: deleteCategory, isLoading } = useDeleteCategory();

  const handleDelete = () =>
    onDelete
      ? onDelete()
      : category.id &&
        deleteCategory({ categoryId: category.id }, { onSettled: onClose });

  const getProps = () => {
    if (hasChildren(category))
      return {
        title: t('categories.delete.with_children.title', {
          name: `"${category.name}"`,
        }),
        description: t('categories.delete.with_children.description'),
        onConfirm: onClose,
        confirmLabel: t('general:understood'),
      };
    if (category.amountOfCourses > 0)
      return {
        title: t('categories.delete.with_courses.title'),
        description: t('categories.delete.with_courses.description', {
          name: `"${category.name}"`,
        }),
        onConfirm: handleDelete,
        confirmLabel: t('general:delete_anyway'),
      };

    return {
      title: t('categories.delete.confirm.title', {
        name: `"${category.name}"`,
      }),
      description: t('categories.delete.confirm.description'),
      onConfirm: handleDelete,
      confirmLabel: t('general:delete'),
    };
  };

  const { confirmLabel, onConfirm, title, description } = getProps();

  const handleAction =
    (callback: Function) => (event: MouseEvent<HTMLButtonElement>) => {
      event.stopPropagation();
      callback();
    };

  return (
    <Dialog
      onClose={onClose}
      title={title}
      textBody={description}
      primaryButtonProps={{
        children: confirmLabel,
        loading: isLoading,
        disabled: isLoading,
        onClick: handleAction(onConfirm),
      }}
      secondaryButtonProps={{
        children: t('general:cancel'),
        disabled: isLoading,
        onClick: handleAction(onClose),
      }}
    />
  );
};

export default DeleteCategoryModal;
