import { RouterProvider } from 'react-router';
import createLoader from '@ablogcms/react-router/list-view/create-loader';
import createRouter from '@ablogcms/react-router/list-view/create-router';
import { AcmsContextProvider } from '@stores/acms';
import Announce from '@ablogcms/components/announce';
import EntryAdmin from '../components/entry-admin/entry-admin';
import { preloadEntries } from '../hooks/use-entries-swr';
import { preloadColumnConfig } from '../hooks/use-entry-column-config-swr';
import { preloadCustomColumns } from '../hooks/use-entry-custom-columns-swr';

const loader = createLoader({
  id: 'entry-admin',
  admin: 'entry_index',
  onLoad: ({ context, url }) => {
    Promise.all([preloadEntries(context, url.searchParams), preloadColumnConfig(), preloadCustomColumns()]);
  },
});

const router = createRouter({
  contextProvider: AcmsContextProvider,
  element: (
    <EntryAdmin
      getValues={ACMS.Config.entryAdminConfig.getValues}
      getValuesOptions={ACMS.Config.entryAdminConfig.getValuesOptions}
      getActions={ACMS.Config.entryAdminConfig.getActions}
      getBulkActions={ACMS.Config.entryAdminConfig.getBulkActions}
      getMenus={ACMS.Config.entryAdminConfig.getMenus}
      getColumns={ACMS.Config.entryAdminConfig.getColumns}
    />
  ),
  errorElement: (
    <Announce
      title={ACMS.i18n('entry_index.error.unknown.title')}
      message={ACMS.i18n('entry_index.error.unknown.message')}
    />
  ),
  loader,
});

function EntryAdminRoot() {
  return <RouterProvider router={router} />;
}

export default EntryAdminRoot;
