// Libs
// -----------------------------------------------------------------------------
import { useCallback } from 'react';

// App
// -----------------------------------------------------------------------------
import { showConfirmModal } from 'components/Modals/ConfirmModal/ConfirmModal';
import { runAsyncWithMessages } from 'components/Messages';
import { GenericDashboardLocale } from '../types';
import { GenericDataStore } from 'stores/GenericDataStore';
import { useCommonMessages } from 'components/i18n';
import { GenericDashboardUiStore } from 'stores/GenericDashboardUiStore';

/**
 * Получить функцию для удаления одного элемента таблицы.
 */
export const useItemDelete = <T, TB = T>(
  locale: GenericDashboardLocale,
  dataStore: GenericDataStore<T, TB>,
  uiStore?: GenericDashboardUiStore<T>,
): ((id: number | string) => void) => {
  const commonLocale = useCommonMessages();

  return useCallback(
    (id: number | string): void => {
      showConfirmModal({
        title: locale.deletionConfirmation,
        okType: 'danger',
        action: async () => {
          await runAsyncWithMessages(
            async () => {
              await dataStore.delete(id);
            },
            {
              okMessage: locale.deletionSuccess,
              errorMessage: locale.deletionError,
            },
          );

          if (uiStore) {
            uiStore.setSelectedRowKeys([]);
          }
          dataStore.setCurrentPage(1);
          await dataStore.fetchForCurrentPage();
        },
        okText: commonLocale.confirmText.ok,
        cancelText: commonLocale.confirmText.cancel,
      });
    },
    [commonLocale, locale, dataStore, uiStore],
  );
};
