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

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

    const { gridConfig } = initListPage({
      grid: {
        gridjs,
        container: '#permissions-grid',
        dataUrl: 'admin/permissions/data',
        appBase,
        columns: [
          { name: labels.description || 'Description', sort: true },
          { name: labels.permissionKey || 'Permission key', sort: true },
          {
            name: labels.status || 'Status',
            sort: true,
            formatter: (cell) => cell
              ? gridjs.html(`<span class="badge" data-variant="success">${labels.active || 'Active'}</span>`)
              : gridjs.html(`<span class="badge" data-variant="danger">${labels.inactive || 'Inactive'}</span>`),
          },
          {
            name: labels.system || 'System',
            sort: false,
            formatter: (cell) => cell
              ? gridjs.html(`<span class="badge" data-variant="neutral">${labels.system || 'System'}</span>`)
              : gridjs.html(''),
          },
          { name: labels.created || 'Created', sort: true, formatter: (cell) => badgeHtml(gridjs, cell) },
          { name: 'ID', hidden: true },
        ],
        sortColumns: ['description', 'key', 'active', null, 'created', null],
        paginationLimit: 10,
        language: config.gridLang ?? {},
        mapData: (data) => data.data.map((row) => [
          row.description,
          row.key,
          row.active,
          row.is_system,
          row.created,
          row.id,
        ]),
        rowInteraction: { linkColumn: 0 },
        rowDblClick: {
          getUrl: (row) => {
            const id = row?.cells?.[5]?.data;
            return id ? new URL(`admin/permissions/edit/${id}`, appBase).toString() : '';
          },
        },
        search: gridSearch,
        filterSchema,
        urlSync: true,
      },
      filters: {
        mode: 'drawer',
        chipMeta: filterChipMeta,
        watchInputs: ['#permission-search'],
      },
    }) || {};

    return gridConfig;
  },
});
