import { createListPageModule } from '../core/app-list-page-module.js';

createListPageModule({
  configId: 'admin-mail-log-index',
  moduleId: 'admin-mail-log-index',
  missingGridMessage: 'Mail log grid init failed: Grid.js missing',
  initErrorMessage: 'Mail log grid init failed',
  setup: ({ config, gridjs, appBase, initListPage }) => {
    const gridSearch = config.gridSearch ?? null;
    const filterSchema = config.filterSchema ?? [];
    const filterChipMeta = config.filterChipMeta ?? [];
    const labels = config.labels ?? {};

    const { gridConfig } = initListPage({
      grid: {
        gridjs,
        container: '#mail-log-grid',
        dataUrl: 'admin/mail-log/data',
        appBase,
        columns: [
          {
            name: labels.created || 'Created',
            sort: true,
          },
          {
            name: labels.status || 'Status',
            sort: true,
            formatter: (cell) => {
              if (!cell || typeof cell !== 'object') {
                return gridjs.html('');
              }
              const variant = cell.variant || 'neutral';
              const label = cell.label || '';
              return gridjs.html(`<span class="badge" data-variant="${variant}">${label}</span>`);
            },
          },
          {
            name: labels.recipient || 'Recipient',
            sort: true,
            formatter: (cell) => {
              if (!cell || typeof cell !== 'object') {
                return gridjs.html(String(cell ?? ''));
              }
              return gridjs.html(String(cell ?? ''));
            },
          },
          {
            name: labels.subject || 'Subject',
            sort: true,
          },
          {
            name: labels.template || 'Template',
            sort: false,
          },
          {
            name: 'ID',
            hidden: true,
          },
        ],
        sortColumns: ['created_at', 'status', 'to_email', 'subject', null, null],
        paginationLimit: 10,
        language: config.gridLang ?? {},
        mapData: (data) => data.data.map((row) => [
          row.created_at,
          {
            variant: row.status_badge,
            label: row.status_label,
          },
          row.to_email,
          row.subject,
          row.template || '-',
          row.id,
        ]),
        rowInteraction: { linkColumn: 3 },
        search: gridSearch,
        filterSchema,
        urlSync: true,
        rowDblClick: {
          getUrl: (rowData) => {
            const id = rowData?.cells?.[5]?.data;
            return id ? new URL(`admin/mail-log/view/${id}`, appBase).toString() : '';
          },
        },
      },
      filters: {
        mode: 'drawer',
        chipMeta: filterChipMeta,
        watchInputs: ['#mail-log-search'],
      },
    }) || {};

    return gridConfig;
  },
});
