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

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

  const initTenantsGrid = () => {
    const tenantUuidIndex = 8;
    const tenantDescriptionIndex = 1;
    const formatBadge = (value) => badgeHtml(gridjs, value);
    const initialsForRow = (row) => {
      const descriptionCell = row?.cells?.[tenantDescriptionIndex]?.data;
      const label = typeof descriptionCell === 'object' && descriptionCell !== null
        ? String(descriptionCell.label ?? '')
        : String(descriptionCell ?? '');
      const initial = label.trim().charAt(0).toUpperCase();
      return initial || '?';
    };
    const formatStatus = (value) => {
      if (!value || typeof value !== 'object') {
        return gridjs.html('-');
      }
      const variant = String(value.variant || 'neutral');
      const label = String(value.label || '-');
      return gridjs.html(`<span class="badge" data-variant="${variant}">${label}</span>`);
    };
    const formatTheme = (cell) => {
      if (!cell || typeof cell !== 'object') {
        return gridjs.html('');
      }
      const themeLabel = escapeHtml(cell.label ?? '');
      const label = cell.is_override ? themeLabel : `${themeLabel} (${escapeHtml(labels.default || 'Default')})`;
      return gridjs.html(label);
    };
    const formatSso = (cell) => {
      if (!cell || typeof cell !== 'object') {
        return gridjs.html('');
      }
      if (!cell.enabled) {
        return gridjs.html(escapeHtml(labels.inactive || 'Inactive'));
      }
      if (cell.microsoft_only) {
        return gridjs.html(escapeHtml(labels.microsoftOnly || 'Microsoft only'));
      }
      return gridjs.html(escapeHtml(labels.active || 'Active'));
    };
    const formatCount = (value) => {
      const number = Number(value ?? 0);
      return Number.isFinite(number) ? number : 0;
    };
    const gridOptions = {
      gridjs: window.gridjs,
      container: '#tenants-grid',
      dataUrl: 'admin/tenants/data',
      appBase,
      columns: [
        {
          name: labels.avatar || 'Avatar',
          sort: false,
          formatter: (cell, row) => {
            if (!cell) {
              const initials = escapeHtml(initialsForRow(row));
              return gridjs.html(`<span class="grid-avatar grid-avatar-tenant grid-avatar-placeholder">${initials}</span>`);
            }
            const uuid = encodeURIComponent(String(cell));
            const src = new URL(`admin/tenants/avatar-file?uuid=${uuid}&size=64`, appBase).toString();
            const full = new URL(`admin/tenants/avatar-file?uuid=${uuid}&size=256`, appBase).toString();
            return gridjs.html(`<a data-fslightbox="tenant-avatars" href="${full}"><img class="grid-avatar grid-avatar-tenant" src="${src}" alt="" loading="lazy"></a>`);
          },
        },
        {
          name: labels.description || 'Description',
          sort: true,
          formatter: (cell) => {
            if (!cell || typeof cell !== 'object') {
              return gridjs.html(escapeHtml(String(cell ?? '')));
            }
            const label = escapeHtml(cell.label ?? '');
            return gridjs.html(label);
          },
        },
        {
          name: labels.status || 'Status',
          sort: false,
          formatter: (cell) => formatStatus(cell),
        },
        {
          name: labels.theme || 'Theme',
          sort: true,
          formatter: (cell) => formatTheme(cell),
        },
        {
          name: labels.sso || 'SSO',
          sort: true,
          formatter: (cell) => formatSso(cell),
        },
        {
          name: labels.activeUsers || 'Active users',
          sort: true,
          formatter: (cell) => formatCount(cell),
        },
        {
          name: labels.inactiveUsers || 'Inactive users',
          sort: true,
          formatter: (cell) => formatCount(cell),
        },
        {
          name: labels.created || 'Created',
          sort: true,
          formatter: (cell) => formatBadge(cell),
        },
        {
          name: 'UUID',
          hidden: true,
        },
      ],
      sortColumns: [null, 'description', 'status', 'theme', 'sso', 'active_users', 'inactive_users', 'created', null],
      paginationLimit: 10,
      language: config.gridLang ?? {},
      mapData: (data) => data.data.map((row) => [
        row.has_avatar ? row.uuid : '',
        {
          label: row.description,
          is_default: row.is_default ? 1 : 0,
        },
        { variant: row.status_badge || 'neutral', label: row.status_label || row.status || '-' },
        row.theme ?? null,
        row.sso ?? null,
        row.active_users ?? 0,
        row.inactive_users ?? 0,
        row.created,
        row.uuid,
      ]),
      actions: { enabled: false },
      search: gridSearch,
      filterSchema,
      urlSync: true,
      rowDataset: (row) => ({
        uuid: row?.cells?.[tenantUuidIndex]?.data,
      }),
      rowDblClick: {
        getUrl: (rowData) => {
          const uuid = rowData?.cells?.[tenantUuidIndex]?.data;
          return uuid ? new URL(`admin/tenants/edit/${uuid}`, appBase).toString() : '';
        },
      },
    };
    const { gridConfig } = initStandardListPage({
      grid: gridOptions,
      filters: {
        mode: 'drawer',
        chipMeta: filterChipMeta,
        watchInputs: ['#tenant-search'],
      },
    });
    if (!gridConfig || !gridConfig.grid) {
      warnOnce('UI_INIT_FAIL', 'Tenants grid init failed', { module: 'admin-tenants-index', component: 'grid' });
      return null;
    }
    return gridConfig;
  };

  initTenantsGrid();
}
