import { createServerGrid } from '../core/app-grid-factory.js';
import { readPageConfig } from '../core/app-page-config.js';
import { getAppBase } from './app-list-utils.js';

const config = readPageConfig('admin-scheduled-jobs-edit');
if (config) {
  const appBase = getAppBase();
  const labels = config.labels ?? {};
  const searchConfig = config.search ?? { input: '#scheduled-job-runs-search', param: 'search', debounce: 250 };
  const filterConfig = Array.isArray(config.filters) ? config.filters : [
    { input: '#scheduled-job-runs-status-filter', param: 'status' },
    { input: '#scheduled-job-runs-trigger-filter', param: 'trigger_type' },
  ];

  const scheduleTypeInput = document.querySelector('#scheduled-job-schedule-type');
  const scheduleTimeWrap = document.querySelector('[data-schedule-time-wrap]');
  const scheduleWeekdaysWrap = document.querySelector('[data-schedule-weekdays-wrap]');

  const updateScheduleVisibility = () => {
    const type = (scheduleTypeInput?.value || 'daily').toLowerCase();
    const showTime = type === 'daily' || type === 'weekly';
    const showWeekdays = type === 'weekly';
    if (scheduleTimeWrap) {
      scheduleTimeWrap.hidden = !showTime;
    }
    if (scheduleWeekdaysWrap) {
      scheduleWeekdaysWrap.hidden = !showWeekdays;
    }
  };

  if (scheduleTypeInput) {
    scheduleTypeInput.addEventListener('change', updateScheduleVisibility);
    updateScheduleVisibility();
  }

  createServerGrid({
    gridjs: window.gridjs,
    container: '#scheduled-job-runs-grid',
    dataUrl: `admin/scheduled-jobs/runs-data/${config.jobId}`,
    appBase,
    columns: [
      {
        name: labels.started || 'Started',
        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.trigger || 'Trigger',
        sort: true,
        formatter: (cell) => {
          if (!cell || typeof cell !== 'object') {
            return '-';
          }
          return String(cell.label || '-');
        },
      },
      {
        name: labels.durationMs || 'Duration (ms)',
        sort: true,
        formatter: (cell) => (Number(cell) > 0 ? `${cell}` : '-'),
      },
      {
        name: labels.errorCode || 'Error code',
        sort: false,
      },
      {
        name: labels.user || 'User',
        sort: false,
      },
      {
        name: labels.runUuid || 'Run UUID',
        sort: false,
      },
    ],
    sortColumns: ['started_at', 'status', 'trigger_type', 'duration_ms', null, 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 || '',
      },
      { label: row.trigger_type_label || row.trigger_type || '-' },
      row.duration_ms || 0,
      row.error_code || '-',
      row.actor_label || '-',
      row.run_uuid || '-',
    ]),
    actions: {
      enabled: false,
    },
    search: searchConfig,
    filters: filterConfig,
    urlSync: false,
  });
}
