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

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

    const { gridConfig } = initListPage({
      grid: {
        gridjs,
        container: '#helpdesk-search-grid',
        dataUrl: config.dataUrl || 'helpdesk/search-data',
        appBase,
        columns: [
          {
            name: labels.debtorNo || 'Debtor No.',
            sort: true,
            formatter: (cell) => {
              const debtorNo = escapeHtml(cell?.no || '');
              const detailUrl = String(cell?.url || '').trim();
              if (detailUrl === '') {
                return gridjs.html(debtorNo);
              }
              const href = escapeHtml(withCurrentListReturn(detailUrl));
              return gridjs.html(`<a href="${href}">${debtorNo}</a>`);
            },
          },
          { name: labels.name || 'Name', sort: true },
          { name: labels.city || 'City', sort: true },
          { name: labels.phone || 'Phone', sort: false },
          { name: labels.email || 'E-Mail', sort: false },
          { name: 'detail_url', hidden: true },
        ],
        sortColumns: ['No', 'Name', 'City', null, null, null],
        paginationLimit: 10,
        language: config.gridLang || {},
        mapData: (data) => (data.data || []).map((row) => [
          { no: row.No || '', url: row.detail_url || '' },
          row.Name || '',
          row.City || '',
          row.Phone_No || '',
          row.E_Mail || '',
          row.detail_url || '',
        ]),
        search: config.gridSearch || null,
        filterSchema: config.filterSchema || [],
        urlSync: true,
        rowInteraction: { linkColumn: 0 },
        rowDblClick: {
          getUrl: (rowData) => rowData?.cells?.[5]?.data || '',
        },
      },
      filters: {
        mode: 'drawer',
        chipMeta: config.filterChipMeta || {},
        watchInputs: ['#helpdesk-search-input'],
      },
    }) || {};

    return gridConfig;
  },
});
