import { createListPageModule } from '../core/app-list-page-module.js';

createListPageModule({
  configId: 'admin-scheduled-jobs-index',
  moduleId: 'admin-scheduled-jobs-index',
  missingGridMessage: 'Scheduled jobs grid init failed: Grid.js missing',
  initErrorMessage: 'Scheduled jobs grid init failed',
  setup: ({ config, gridjs, appBase, initListPage }) => {
    const gridSearch = config.gridSearch ?? null;
    const filterSchema = config.filterSchema ?? [];
    const filterChipMeta = config.filterChipMeta ?? [];
    const labels = config.labels ?? {};

    const { gridConfig } = initListPage({
      grid: {
        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,
        ]),
        rowInteraction: { linkColumn: 0 },
        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() : '';
          },
        },
      },
      filters: {
        mode: 'drawer',
        chipMeta: filterChipMeta,
        watchInputs: ['#scheduled-jobs-search'],
      },
    }) || {};

    return gridConfig;
  },
});
