import { initStandardListPage } from '../core/app-grid-factory.js';
import { readPageConfig } from '../core/app-page-config.js';
import { warnOnce } from '../core/app-dom.js';
import { getAppBase } from './app-list-utils.js';

const config = readPageConfig('admin-mail-log-index');
if (config) {
  const appBase = getAppBase();
  const gridSearch = config.gridSearch ?? null;
  const filterSchema = config.filterSchema ?? [];
  const filterChipMeta = config.filterChipMeta ?? [];
  const labels = config.labels ?? {};

  const initMailLogGrid = () => {
    const gridOptions = {
      gridjs: window.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,
      ]),
      actions: {
        enabled: false,
      },
      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() : '';
        },
      },
    };
    const { gridConfig } = initStandardListPage({
      grid: gridOptions,
      filters: {
        mode: 'drawer',
        chipMeta: filterChipMeta,
        watchInputs: ['#mail-log-search'],
      },
    });
    if (!gridConfig || !gridConfig.grid) {
      warnOnce('UI_INIT_FAIL', 'Mail log grid init failed', { module: 'admin-mail-log-index', component: 'grid' });
      return null;
    }
    return gridConfig;
  };

  initMailLogGrid();
}
