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 } from './app-list-utils.js';

const config = readPageConfig('admin-user-lifecycle-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 gridOptions = {
    gridjs: window.gridjs,
    container: '#user-lifecycle-audit-grid',
    dataUrl: 'admin/user-lifecycle-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.action || 'Action', sort: true },
      { name: labels.trigger || 'Trigger', sort: true },
      { name: labels.targetEmail || 'Target email', sort: false },
      { name: labels.targetUuid || 'Target UUID', sort: false },
      { name: labels.reasonCode || 'Reason code', sort: false },
      { name: labels.restoredAt || 'Restored at', sort: true },
      { name: 'ID', hidden: true },
    ],
    sortColumns: ['created_at', 'status', 'action', 'trigger_type', null, null, null, 'restored_at', null],
    paginationLimit: 10,
    language: config.gridLang ?? {},
    mapData: (data) => data.data.map((row) => [
      row.created_at,
      { variant: row.status_badge, label: row.status_label || row.status || '' },
      row.action_label || row.action || '-',
      row.trigger_type_label || row.trigger_type || '-',
      row.target_user_email || '-',
      row.target_user_uuid || '-',
      row.reason_code || '-',
      row.restored_at || '-',
      row.id,
    ]),
    actions: { enabled: false },
    search: gridSearch,
    filterSchema,
    urlSync: true,
    rowDblClick: {
      getUrl: (rowData) => {
        const id = rowData?.cells?.[8]?.data;
        return id ? new URL(`admin/user-lifecycle-audit/view/${id}`, appBase).toString() : '';
      },
    },
  };

  const { gridConfig } = initStandardListPage({
    grid: gridOptions,
    filters: {
      mode: 'drawer',
      chipMeta: filterChipMeta,
      watchInputs: ['#user-lifecycle-audit-search'],
    },
  });

  if (!gridConfig || !gridConfig.grid) {
    warnOnce('UI_INIT_FAIL', 'User lifecycle audit grid init failed', { module: 'admin-user-lifecycle-audit-index', component: 'grid' });
  }
}
