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

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

    const gridOptions = {
      gridjs,
      container: '#security-templates-grid',
      dataUrl: config.dataUrl || 'security/templates-data',
      appBase,
      columns: [
        {
          name: labels.productName || 'Product',
          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.productCode || 'Code', sort: true },
        { name: labels.itemCount || 'Checklist items', sort: false },
        {
          name: labels.active || 'Active',
          sort: true,
          formatter: (cell) => {
            const active = cell === true || cell === 'true';
            const label = active ? (labels.yes || 'Yes') : (labels.no || 'No');
            const variant = active ? 'success' : 'neutral';
            return gridjs.html(`<span class="badge" data-variant="${variant}">${escapeHtml(label)}</span>`);
          },
        },
        { name: labels.updatedAt || 'Updated', sort: true },
        { name: 'edit_url', hidden: true },
      ],
      sortColumns: ['product_name', 'product_code', null, 'active', 'updated_at', null],
      paginationLimit: 20,
      language: config.gridLang || {},
      mapData: (data) => (data.data || []).map((row) => [
        { text: row.product_name || row.product_code || '', url: row.edit_url || '' },
        row.product_code || '',
        String(row.item_count ?? 0),
        row.active === true,
        row.updated_at || '',
        row.edit_url || '',
      ]),
      search: config.gridSearch || null,
      filterSchema: config.filterSchema || [],
      urlSync: true,
      rowInteraction: { linkColumn: 0 },
      rowDblClick: {
        getUrl: (rowData) => rowData?.cells?.[5]?.data || '',
      },
    };

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

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