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-scheduled-jobs-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: '#scheduled-jobs-grid',
    dataUrl: 'admin/scheduled-jobs/data',
    appBase,
    columns: [
      {
        name: labels.job || 'Job',
        sort: true,
        formatter: (cell) => {
          if (!cell || typeof cell !== 'object') {
            return gridjs.html('-');
          }
          const fallbackLabel = String(cell.job_key || '')
            .toLowerCase()
            .replace(/_/g, ' ')
            .replace(/^./, (char) => char.toUpperCase());
          return gridjs.html(cell.label || fallbackLabel || '-');
        },
      },
      {
        name: labels.enabled || 'Enabled',
        sort: true,
        formatter: (cell) => {
          const enabled = Number(cell) === 1;
          const variant = enabled ? 'success' : 'neutral';
          const label = enabled ? (labels.enabled || 'Enabled') : (labels.disabled || 'Disabled');
          return gridjs.html(`<span class="badge" data-variant="${variant}">${label}</span>`);
        },
      },
      { name: labels.nextRun || 'Next run', sort: true },
      { name: labels.schedule || 'Schedule', sort: false },
      { name: labels.lastRun || 'Last run', 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.lastError || 'Last error', sort: false },
      { name: 'ID', hidden: true },
    ],
    sortColumns: ['job_key', 'enabled', 'next_run_at', null, 'last_run_finished_at', 'last_run_status', null, null],
    paginationLimit: 10,
    language: config.gridLang ?? {},
    mapData: (data) => data.data.map((row) => [
      { id: row.id, label: row.label || row.job_key, job_key: row.job_key },
      row.enabled,
      row.next_run_at || '-',
      row.schedule_summary || '-',
      row.last_run_finished_at || '-',
      { variant: row.last_run_status_badge, label: row.last_run_status_label || row.last_run_status || '' },
      row.last_error || '-',
      row.id,
    ]),
    actions: { enabled: false },
    search: gridSearch,
    filterSchema,
    urlSync: true,
    rowDblClick: {
      getUrl: (rowData) => {
        const id = rowData?.cells?.[7]?.data;
        return id ? new URL(`admin/scheduled-jobs/edit/${id}`, appBase).toString() : '';
      },
    },
  };

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

  if (!gridConfig || !gridConfig.grid) {
    warnOnce('UI_INIT_FAIL', 'Scheduled jobs grid init failed', { module: 'admin-scheduled-jobs-index', component: 'grid' });
  }
}
