import { createListPageModule } from '../core/app-list-page-module.js';
import { escapeHtml } from './app-list-utils.js';

createListPageModule({
  configId: 'admin-tenants-index',
  moduleId: 'admin-tenants-index',
  missingGridMessage: 'Tenants grid init failed: Grid.js missing',
  initErrorMessage: 'Tenants grid init failed',
  setup: ({ config, gridjs, appBase, initListPage }) => {
    const filterSchema = config.filterSchema ?? [];
    const filterChipMeta = config.filterChipMeta ?? [];
    const labels = config.labels ?? {};

    const tenantUuidIndex = 2;

    const { gridConfig } = initListPage({
      grid: {
        gridjs,
        container: '#tenants-grid',
        dataUrl: 'admin/tenants/data',
        appBase,
        columns: [
          {
            name: labels.tenant || 'Tenant',
            sort: true,
            width: '75%',
            formatter: (cell) => gridjs.html(escapeHtml(String(cell ?? ''))),
          },
          {
            name: labels.users || 'Users',
            sort: true,
            width: '25%',
            formatter: (cell) => {
              const number = Number(cell ?? 0);
              return gridjs.html(String(Number.isFinite(number) ? number : 0));
            },
          },
          {
            name: 'UUID',
            hidden: true,
          },
        ],
        sortColumns: ['description', 'users', null],
        paginationLimit: 10,
        language: config.gridLang ?? {},
        mapData: (data) => data.data.map((row) => [
          row.description ?? '',
          row.total_users ?? 0,
          row.uuid,
        ]),
        rowInteraction: { linkColumn: 0 },
        search: config.gridSearch ?? null,
        filterSchema,
        urlSync: true,
        rowDataset: (row) => ({
          uuid: row?.cells?.[tenantUuidIndex]?.data,
        }),
        rowDblClick: {
          getUrl: (rowData) => {
            const uuid = rowData?.cells?.[tenantUuidIndex]?.data;
            return uuid ? new URL(`admin/tenants/edit/${uuid}`, appBase).toString() : '';
          },
        },
      },
      filters: {
        mode: 'drawer',
        chipMeta: filterChipMeta,
        watchInputs: ['#tenant-search'],
      },
    }) || {};

    return gridConfig;
  },
});
