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-roles-index');
if (config) {
  const appBase = getAppBase();
  const gridSearch = config.gridSearch ?? null;
  const filterSchema = config.filterSchema ?? [];
  const filterChipMeta = config.filterChipMeta ?? [];
  const labels = config.labels ?? {};

  const initRolesGrid = () => {
    const formatBadge = (value) => badgeHtml(gridjs, value);
    const formatCount = (value) => {
      const number = Number(value ?? 0);
      return Number.isFinite(number) ? number : 0;
    };
    const gridOptions = {
      gridjs: window.gridjs,
      container: '#roles-grid',
      dataUrl: 'admin/roles/data',
      appBase,
      columns: [
        {
          name: labels.description || 'Description',
          sort: true,
          formatter: (cell) => {
            if (!cell || typeof cell !== 'object') {
              return gridjs.html(String(cell ?? ''));
            }
            const label = cell.label ?? '';
            return gridjs.html(`${label}`);
          },
        },
        {
          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.code || 'Code',
          sort: true,
          formatter: (cell) => gridjs.html(String(cell ?? '')),
        },
        {
          name: labels.activeUsers || 'Active users',
          sort: false,
          formatter: (cell) => formatCount(cell),
        },
        {
          name: labels.inactiveUsers || 'Inactive users',
          sort: false,
          formatter: (cell) => formatCount(cell),
        },
        {
          name: labels.permissions || 'Permissions',
          sort: false,
          formatter: (cell) => formatCount(cell),
        },
        {
          name: labels.created || 'Created',
          sort: true,
          formatter: (cell) => formatBadge(cell),
        },
        {
          name: labels.modified || 'Modified',
          sort: true,
          formatter: (cell) => formatBadge(cell),
        },
        {
          name: 'UUID',
          hidden: true,
        },
      ],
      sortColumns: ['description', 'active', 'code', null, null, null, 'created', 'modified', null],
      paginationLimit: 10,
      language: config.gridLang ?? {},
      mapData: (data) => data.data.map((row) => [
        {
          label: row.description,
          is_default: row.is_default ? 1 : 0,
        },
        row.active,
        row.code,
        row.active_users ?? 0,
        row.inactive_users ?? 0,
        row.permission_count ?? 0,
        row.created,
        row.modified,
        row.uuid,
      ]),
      actions: { enabled: false },
      search: gridSearch,
      filterSchema,
      urlSync: true,
      rowDataset: (row) => ({
        uuid: row?.cells?.[8]?.data,
      }),
      rowDblClick: {
        getUrl: (rowData) => {
          const uuid = rowData?.cells?.[8]?.data;
          return uuid ? new URL(`admin/roles/edit/${uuid}`, appBase).toString() : '';
        },
      },
    };

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

  initRolesGrid();
}
