import { initStandardListPage } from '../core/app-grid-factory.js';
import { readPageConfig } from '../core/app-page-config.js';
import { warnOnce } from '../core/app-dom.js';
import { badgeHtml, getAppBase } from './app-list-utils.js';

const config = readPageConfig('admin-permissions-index');
if (config) {
  const appBase = getAppBase();
  const gridSearch = config.gridSearch ?? null;
  const filterSchema = config.filterSchema ?? [];
  const filterChipMeta = config.filterChipMeta ?? [];
  const labels = config.labels ?? {};

  const initPermissionsGrid = () => {
    const gridOptions = {
      gridjs: window.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,
      ]),
      rowDblClick: {
        getUrl: (row) => {
          const id = row?.cells?.[5]?.data;
          return id ? new URL(`admin/permissions/edit/${id}`, appBase).toString() : '';
        },
      },
      search: gridSearch,
      filterSchema,
      urlSync: true,
    };

    const { gridConfig } = initStandardListPage({
      grid: gridOptions,
      filters: {
        mode: 'drawer',
        chipMeta: filterChipMeta,
        watchInputs: ['#permission-search'],
      },
    });
    if (!gridConfig || !gridConfig.grid) {
      warnOnce('UI_INIT_FAIL', 'Permissions grid init failed', { module: 'admin-permissions-index', component: 'grid' });
      return null;
    }
    return gridConfig;
  };

  initPermissionsGrid();
}
