// Libs
// -----------------------------------------------------------------------------
import { useMemo, useCallback } from 'react';
import { observer } from 'mobx-react-lite';
import { TableRowSelection } from 'antd/lib/table/interface';

// App
// -----------------------------------------------------------------------------
import { useStore } from 'stores/StoreProvider';
import { TCommonMessages, useCommonMessages } from 'components/i18n';
import { AccountCard } from './AccountCard/AccountCard';
import { RootStore } from 'stores/RootStore';
import { TypeActionButtonsConfig } from 'components/DashboardTable/components/useActionsWithSelectedCards/types';
import { makeLeftSidebarContent } from 'components/Layout';
import { Page } from 'pages/AppRoutes/constants';
import {
  GenericDashboard,
  useItemDelete,
  useCollectiveDelete,
} from 'components/GenericDashboard';
import { makeAccountsDashboardColumns } from './makeAccountsDashboardColumns';
import { makeAccountsDashboardActions } from './makeAccountsDashboardActions';
import { useAccountsDashboardLocale } from './i18n';
import { TypeAccount, TypeAccountForBackend } from 'types/default';

export const AccountsDashboard = observer((): JSX.Element => {
  const rootStore: RootStore = useStore();
  const dataStore = rootStore.accountsStoreNew;
  const uiStore = rootStore.accountsDashboardUiStore;

  // Общая локализация
  const commonTranslation: TCommonMessages = useCommonMessages();

  // Локализации элементов страницы
  const dashboardLocale = useAccountsDashboardLocale();

  // Содержимое боковой панели
  const leftSideBarContent = makeLeftSidebarContent(
    Page.ACCOUNTS_USER,
    commonTranslation.leftSidebar,
  );

  // Удалить одного пользователя
  const onUserDelete = useItemDelete(dashboardLocale, dataStore, uiStore);

  // Удалить нескольких пользователей
  const onCollectiveUserDelete = useCollectiveDelete(
    dashboardLocale,
    dataStore,
    uiStore,
  );

  // Настройки кнопок коллективных действий
  const actionButtonsConfig = useMemo((): TypeActionButtonsConfig[] => {
    const hasSelected = uiStore.selectedRowKeys.length > 0;
    const action = makeAccountsDashboardActions(
      dashboardLocale,
      {
        onCollectiveDelete: () =>
          onCollectiveUserDelete(uiStore.selectedRowKeys),
      },
      hasSelected,
    );

    return [action.delete];
  }, [dashboardLocale, onCollectiveUserDelete, uiStore.selectedRowKeys]);

  // Проверить является пользователь текущим
  const checkUserIsCurrent = useCallback(
    (entity: TypeAccount): boolean => {
      const currentUserId = rootStore.currentUserStore.user?.id;
      return entity.user.id === currentUserId;
    },
    [rootStore.currentUserStore.user],
  );

  // Колонки таблицы
  const columns = useMemo(
    () =>
      makeAccountsDashboardColumns(
        dashboardLocale,
        {
          onDelete: onUserDelete,
          onEdit: () => uiStore.setIsFormDisabled(false),
        },
        checkUserIsCurrent,
      ),
    [onUserDelete, dashboardLocale, checkUserIsCurrent, uiStore],
  );

  // Отключить чекбокс выбора строки для текущего пользователя
  const getCheckboxProps: TableRowSelection<TypeAccount>['getCheckboxProps'] =
    useCallback(
      (entity: TypeAccount) => {
        const currentUserId = rootStore.currentUserStore.user?.id;

        return {
          disabled: entity.user.id === currentUserId,
        };
      },
      [rootStore.currentUserStore.user],
    );

  return (
    <GenericDashboard<TypeAccount, TypeAccountForBackend>
      uiStore={uiStore}
      dataStore={dataStore}
      sidebarContent={leftSideBarContent}
      locale={dashboardLocale}
      cardComponent={AccountCard}
      columns={columns}
      actionButtonsConfig={actionButtonsConfig}
      enableRowSelection
      getCheckboxProps={getCheckboxProps}
    />
  );
});
