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

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

    const gridOptions = {
      gridjs,
      container: '#security-checks-grid',
      dataUrl: config.dataUrl || 'security/checks-data',
      appBase,
      columns: [
        {
          name: labels.customer || 'Customer',
          sort: true,
          formatter: (cell) => {
            const text = escapeHtml(String(cell?.text || ''));
            const url = String(cell?.url || '').trim();
            if (text === '') {
              return gridjs.html('<span class="text-muted">—</span>');
            }
            if (url === '') {
              return gridjs.html(text);
            }
            return gridjs.html(`<a href="${escapeHtml(withCurrentListReturn(url))}">${text}</a>`);
          },
        },
        { name: labels.domain || 'Domain', sort: true },
        { name: labels.product || 'Software product', 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: labels.owner || 'Owner', sort: true },
        { name: labels.createdAt || 'Created', sort: true },
        { name: 'edit_url', hidden: true },
      ],
      sortColumns: ['debitor_name', 'domain_url', 'product_name', 'status', null, 'created_at', null],
      paginationLimit: 20,
      language: config.gridLang || {},
      mapData: (data) => (data.data || []).map((row) => [
        { text: row.debitor_name || '', url: row.edit_url || '' },
        row.domain_url || '',
        row.product_name || '',
        { label: row.status_label || '', variant: row.status_variant || 'neutral' },
        row.owner_name || '',
        row.created_at || '',
        row.edit_url || '',
      ]),
      search: config.gridSearch || null,
      filterSchema: config.filterSchema || [],
      urlSync: true,
      rowInteraction: { linkColumn: 0 },
      rowDblClick: {
        getUrl: (rowData) => rowData?.cells?.[6]?.data || '',
      },
    };

    const listResult = initListPage({
      grid: gridOptions,
      filters: {
        mode: 'drawer',
        chipMeta: config.filterChipMeta || {},
        watchInputs: ['#security-checks-search-input'],
      },
    });

    return listResult?.gridConfig || null;
  },
});
