import { createListPageModule } from '/js/core/app-list-page-module.js';
import { escapeHtml, withCurrentListReturn } from '/js/pages/app-list-utils.js';

createListPageModule({
  configId: 'helpdesk-software-products',
  moduleId: 'helpdesk-software-products',
  missingGridMessage: 'Helpdesk software products grid init failed: Grid.js missing',
  initErrorMessage: 'Helpdesk software products grid init failed',
  setup: ({ config, gridjs, appBase, initListPage }) => {
    const labels = config.labels || {};
    const editUrlIndex = 4;

    const { gridConfig } = initListPage({
      grid: {
        gridjs,
        container: '#helpdesk-software-products-grid',
        dataUrl: config.dataUrl || 'helpdesk/software-products-data',
        appBase,
        columns: [
          {
            name: labels.code || 'Code',
            sort: true,
            formatter: (cell) => {
              const code = escapeHtml(cell?.code || '');
              const editUrl = String(cell?.url || '').trim();
              if (editUrl === '') {
                return gridjs.html(code);
              }
              const href = escapeHtml(withCurrentListReturn(editUrl));
              return gridjs.html(`<a href="${href}">${code}</a>`);
            },
          },
          { name: labels.bcDescription || 'BC Description', sort: true },
          { name: labels.name || 'Product Name', sort: true },
          {
            name: labels.status || 'Status',
            sort: true,
            formatter: (cell) => {
              const label = escapeHtml(cell?.label || '');
              const variant = cell?.variant || 'neutral';
              return gridjs.html(`<span class="badge" data-variant="${escapeHtml(variant)}">${label}</span>`);
            },
          },
          { name: 'edit_url', hidden: true },
        ],
        sortColumns: ['code', 'bc_description', 'name', 'active', null],
        paginationLimit: 20,
        language: config.gridLang || {},
        mapData: (data) => (data.data || []).map((row) => [
          { code: row.code || '', url: row.edit_url || '' },
          row.bc_description || '',
          row.name || '',
          { label: row.active_label || '', variant: row.active_variant || 'neutral' },
          row.edit_url || '',
        ]),
        search: config.gridSearch || null,
        filterSchema: config.filterSchema || [],
        urlSync: true,
        rowInteraction: { linkColumn: 0 },
        rowDblClick: {
          getUrl: (rowData) => rowData?.cells?.[editUrlIndex]?.data || '',
        },
      },
      filters: {
        mode: 'drawer',
        chipMeta: config.filterChipMeta || {},
        watchInputs: ['#helpdesk-software-products-search-input'],
      },
    }) || {};

    return gridConfig;
  },
});
