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-import-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 profileLabel = (value) => {
    const key = String(value || '').toLowerCase();
    if (key === 'users') {return labels.users || 'Users';}
    if (key === 'departments') {return labels.departments || 'Departments';}
    return key || '-';
  };

  const gridOptions = {
    gridjs: window.gridjs,
    container: '#import-audit-grid',
    dataUrl: 'admin/import-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.profile || 'Profile',
        sort: true,
        formatter: (cell) => profileLabel(cell),
      },
      { name: labels.durationMs || 'Duration (ms)', sort: true, formatter: (cell) => (cell > 0 ? `${cell}` : '-') },
      { name: labels.rowsTotal || 'Rows total', sort: true },
      { name: labels.createdCount || 'Created count', sort: true },
      { name: labels.skippedCount || 'Skipped count', sort: true },
      { name: labels.failedCount || 'Failed count', sort: true },
      {
        name: labels.user || 'User',
        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: 'ID', hidden: true },
    ],
    sortColumns: ['started_at', 'status', 'profile_key', 'duration_ms', 'rows_total', 'created_count', 'skipped_count', 'failed_count', null, null],
    paginationLimit: 10,
    language: config.gridLang ?? {},
    mapData: (data) => data.data.map((row) => [
      row.started_at,
      { variant: row.status_badge, label: row.status_label || row.status || '' },
      row.profile_key,
      row.duration_ms,
      row.rows_total,
      row.created_count,
      row.skipped_count,
      row.failed_count,
      { uuid: row.user_uuid || '', label: row.user_label || '-' },
      row.id,
    ]),
    actions: { enabled: false },
    search: gridSearch,
    filterSchema,
    urlSync: true,
    rowDblClick: {
      getUrl: (rowData) => {
        const id = rowData?.cells?.[9]?.data;
        return id ? new URL(`admin/import-audit/view/${id}`, appBase).toString() : '';
      },
    },
  };

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

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