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

createListPageModule({
  configId: 'settings-user-lifecycle-audit-panel',
  moduleId: 'settings-user-lifecycle-audit-panel',
  missingGridMessage: 'User lifecycle audit grid init failed: Grid.js missing',
  initErrorMessage: 'User lifecycle audit grid init failed',
  setup: ({ config, gridjs, appBase, initListPage }) => {
    const labels = config.labels ?? {};
    const dataUrl = String(config.dataUrl || 'audit/settings-user-lifecycle/audit-data');
    const gridSearch = config.gridSearch ?? null;
    const filterSchema = config.filterSchema ?? [];
    const filterChipMeta = config.filterChipMeta ?? [];

    const { gridConfig } = initListPage({
      grid: {
        gridjs,
        container: '#settings-user-lifecycle-audit-grid',
        dataUrl,
        appBase,
        columns: [
          { name: labels.created || 'Created', sort: true },
          {
            name: labels.status || 'Status',
            sort: true,
            formatter: (cell) => {
              if (!cell || typeof cell !== 'object') {
                return gridjs.html('-');
              }
              return gridjs.html(`<span class="badge" data-variant="${cell.variant || 'neutral'}">${cell.label || '-'}</span>`);
            },
          },
          {
            name: labels.action || 'Action',
            sort: true,
            formatter: (cell, row) => {
              const id = row?.cells?.[8]?.data;
              const label = String(cell || '-');
              if (!id) {
                return gridjs.html(label);
              }
              return gridjs.html(`<a href="#" class="app-grid-link-cell" data-lifecycle-drawer-trigger>${label}</a>`);
            },
          },
          { name: labels.trigger || 'Trigger', sort: true },
          { name: labels.targetEmail || 'Target email', sort: false },
          { name: labels.targetUuid || 'Target UUID', sort: false },
          { name: labels.reasonCode || 'Reason code', sort: false },
          { name: labels.restoredAt || 'Restored at', sort: true },
          { name: 'ID', hidden: true },
        ],
        sortColumns: ['created_at', 'status', 'action', 'trigger_type', null, null, null, 'restored_at', null],
        paginationLimit: 10,
        language: config.gridLang ?? {},
        mapData: (data) => data.data.map((row) => [
          row.created_at,
          { variant: row.status_badge, label: row.status_label || row.status || '' },
          row.action_label || row.action || '-',
          row.trigger_type_label || row.trigger_type || '-',
          row.target_user_email || '-',
          row.target_user_uuid || '-',
          row.reason_code || '-',
          row.restored_at || '-',
          row.id,
        ]),
        rowInteraction: { linkColumn: false },
        search: gridSearch,
        filterSchema,
        urlSync: true,
        rowDataset: (row) => ({
          'audit-id': row?.cells?.[8]?.data ? String(row.cells[8].data) : '',
        }),
        rowDblClick: {
          getUrl: (rowData) => {
            const id = rowData?.cells?.[8]?.data;
            return id ? new URL(`admin/settings/user-lifecycle#lifecycle-audit/${id}`, appBase).toString() : '';
          },
        },
      },
      filters: {
        mode: 'drawer',
        chipMeta: filterChipMeta,
        watchInputs: ['#user-lifecycle-audit-search'],
      },
    }) || {};

    initDetailDrawer({
      gridConfig,
      triggerSelector: '[data-lifecycle-drawer-trigger]',
      rowUuidAttr: 'audit-id',
      fetchUrl: (id) => new URL(`audit/settings-user-lifecycle/audit-fragment/${id}`, appBase).toString(),
      fullUrl: (id) => new URL(`admin/settings/user-lifecycle#lifecycle-audit/${id}`, appBase).toString(),
      hashPrefix: 'lifecycle-audit',
    });

    return gridConfig;
  },
});
