import { createListPageModule } from '/js/core/app-list-page-module.js';
import { bindBulkVisibility } from '/js/components/app-bulk-selection.js';
import { confirmDialog } from '/js/core/app-confirm-dialog.js';
import { postForm } from '/js/core/app-http.js';
import { escapeHtml, withCurrentListReturn } from '/js/pages/app-list-utils.js';

createListPageModule({
  configId: 'helpdesk-handovers',
  moduleId: 'helpdesk-handovers',
  missingGridMessage: 'Helpdesk handovers grid init failed: Grid.js missing',
  initErrorMessage: 'Helpdesk handovers grid init failed',
  setup: ({ config, gridjs, appBase, initListPage }) => {
    const labels = config.labels || {};
    const canManage = config.canManage || false;

    // Column layout: Domain | Status | Customer | Product | Created | Created by | (edit_url hidden)
    // With selection: checkbox is prepended by grid factory, shifting indices +1
    const editUrlIndex = canManage ? 7 : 6;
    const domainColumnIndex = canManage ? 1 : 0;

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

    if (canManage && gridjs.plugins?.selection?.RowSelection) {
      gridOptions.selection = {
        enabled: true,
        id: 'selectRow',
        component: gridjs.plugins.selection.RowSelection,
        selectAllLabel: labels.selectAll || 'Select all',
        props: {
          id: (row) => row.cell(domainColumnIndex).data?.id || '',
        },
        getSelectedIds: ({ container }) =>
          Array.from(container.querySelectorAll('.gridjs-tr-selected'))
            .map((tr) => {
              const link = tr.querySelector('a[href]');
              if (!link) return '';
              const href = link.getAttribute('href') || '';
              const match = href.match(/\/edit\/(\d+)/);
              return match ? match[1] : '';
            })
            .filter(Boolean),
      };
    }

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

    const gridConfig = listResult?.gridConfig || null;
    if (!canManage || !gridConfig) {
      return gridConfig;
    }

    bindBulkVisibility({
      containerSelector: '#helpdesk-handovers-grid',
      buttonSelector: '[data-handovers-bulk]',
    });

    const bulkButtons = Array.from(document.querySelectorAll('[data-handovers-bulk]'));
    bulkButtons.forEach((button) => {
      button.addEventListener('click', async () => {
        const action = button.dataset.handoversBulk || '';
        const ids = gridConfig.selection?.getSelectedIds?.() || [];
        if (!ids.length || action !== 'delete') {
          return;
        }

        const confirmed = await confirmDialog.confirm({
          message: labels.bulkDeleteConfirm || 'Delete selected handovers?',
          actionKind: 'delete',
        });
        if (!confirmed) {
          return;
        }

        const body = new URLSearchParams({
          ids: ids.join(','),
          [config.csrfKey]: config.csrfToken,
        });

        try {
          const data = await postForm(new URL('helpdesk/handovers/bulk/delete', appBase).toString(), body);
          if (data?.ok !== true) {
            throw new Error('Bulk delete failed');
          }
          gridConfig.selection?.clear?.();
          gridConfig.grid?.forceRender();
        } catch {
          window.location.reload();
        }
      });
    });

    return gridConfig;
  },
});
