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

// App
// -----------------------------------------------------------------------------
import { GenericDataStore } from 'stores/GenericDataStore';
import { InterfaceWithIdAndName } from 'types/default';
import {
  openNotificationError,
  openNotificationSuccess,
  useProgressNotification,
} from 'components/Messages';
import { Notification } from 'components/types';
import { useCommonMessages } from 'components/i18n';

// Интерфейс расширенного GenericDataStore с поддержкой импорта
interface InterfaceDataStoreWithImport<
  T extends InterfaceWithIdAndName,
  TB extends InterfaceWithIdAndName = T,
> extends GenericDataStore<T, TB> {
  importData: (data: FormData) => Promise<void>;
}

// Интерфейс локали с полями уведомлений импорта
interface InterfaceLocaleWithImportMessages {
  importSuccessTitle: string;
  importSuccessSubtitle?: string;
  importFailureTitle: string;
  importFailureSubtitle?: string;
}

export const useImportData = <
  T extends InterfaceWithIdAndName,
  TB extends InterfaceWithIdAndName = T,
>(
  dataStore: InterfaceDataStoreWithImport<T, TB>,
  dashboardLocale: InterfaceLocaleWithImportMessages,
): ((value: FormData) => Promise<void>) => {
  const commonLocale = useCommonMessages();

  // Показать/скрыть уведомление с прогрессом операции
  const { activateProgressMessage, stopProgressMessage } =
    useProgressNotification({
      key: 'progress',
      title: commonLocale.notification[Notification.ProgressTitle],
      makeDescription: (seconds) =>
        seconds
          ? commonLocale.notification[Notification.ProgressSubTitle](seconds)
          : '',
    });

  return useCallback(
    async (value: FormData): Promise<void> => {
      activateProgressMessage();
      try {
        await dataStore.importData(value);

        stopProgressMessage();

        dataStore.setCurrentPage(1);

        await dataStore.fetchForCurrentPage();

        openNotificationSuccess({
          messageTitle: dashboardLocale.importSuccessTitle,
          messageDescription: dashboardLocale.importSuccessSubtitle,
        });
      } catch {
        stopProgressMessage();
        openNotificationError({
          messageTitle: dashboardLocale.importFailureTitle,
        });
      }
    },
    [dataStore, dashboardLocale, activateProgressMessage, stopProgressMessage],
  );
};
