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

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

  const initSystemAuditGrid = () => {
    const gridOptions = {
      gridjs: window.gridjs,
      container: '#system-audit-grid',
      dataUrl: 'admin/system-audit/data',
      appBase,
      columns: [
        { name: labels.created || 'Created', sort: true },
        {
          name: labels.status || 'Status',
          sort: true,
          formatter: (cell) => {
            if (!cell || typeof cell !== 'object') {
              return gridjs.html('');
            }
            return gridjs.html(`<span class="badge" data-variant="${cell.variant || 'neutral'}">${cell.label || ''}</span>`);
          },
        },
        { name: labels.event || 'Event', sort: true },
        { name: labels.channel || 'Channel', sort: true },
        {
          name: labels.actor || 'Actor',
          sort: false,
          formatter: (cell) => {
            if (!cell || typeof cell !== 'object') {
              return gridjs.html('-');
            }
            const label = cell.label || '-';
            if (!cell.uuid) {
              return gridjs.html(label);
            }
            const url = withCurrentListReturn(new URL(`admin/users/edit/${cell.uuid}`, appBase).toString());
            return gridjs.html(`<a href="${url}">${label}</a>`);
          },
        },
        { name: labels.targetType || 'Target type', sort: false },
        {
          name: labels.requestId || 'Request ID',
          sort: false,
          formatter: (cell) => (cell ? gridjs.html(`<code>${String(cell).slice(0, 8)}</code>`) : gridjs.html('-')),
        },
        {
          name: labels.errorCode || 'Error code',
          sort: false,
          formatter: (cell) => (cell ? gridjs.html(`<code>${String(cell)}</code>`) : gridjs.html('-')),
        },
        { name: 'ID', hidden: true },
      ],
      sortColumns: ['created_at', 'outcome', 'event_type', 'channel', null, null, null, null, null],
      paginationLimit: 10,
      language: config.gridLang ?? {},
      mapData: (data) => data.data.map((row) => [
        row.created_at,
        {
          variant: row.outcome_badge,
          label: String(row.outcome_label || row.outcome || ''),
        },
        row.event_type,
        row.channel,
        {
          uuid: row.actor_user_uuid || '',
          label: row.actor_user_label || '-',
        },
        row.target_type || '-',
        row.request_id || '',
        row.error_code || '',
        row.id,
      ]),
      actions: {
        enabled: false,
      },
      search: gridSearch,
      filterSchema,
      rowDblClick: {
        getUrl: (rowData) => {
          const id = rowData?.cells?.[8]?.data;
          return id ? new URL(`admin/system-audit/view/${id}`, appBase).toString() : '';
        },
      },
    };
    const { gridConfig } = initStandardListPage({
      grid: gridOptions,
      filters: {
        mode: 'drawer',
        chipMeta: filterChipMeta,
        watchInputs: ['#system-audit-search'],
      },
    });
    return gridConfig;
  };

  const gridConfig = initSystemAuditGrid();
  if (!gridConfig || !gridConfig.grid) {
    warnOnce('UI_INIT_FAIL', 'System audit grid init failed', { module: 'admin-system-audit-index', component: 'grid' });
  }
}
