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, getAppBase } from './app-list-utils.js';

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

  const initDepartmentsGrid = () => {
    const formatBadge = (value) => badgeHtml(gridjs, value);
    const formatCount = (value) => {
      const number = Number(value ?? 0);
      return Number.isFinite(number) ? number : 0;
    };
    const statusLabels = {
      active: labels.active || 'Active',
      inactive: labels.inactive || 'Inactive',
    };
    const formatStatus = (value) => {
      const normalized = String(value ?? '1').toLowerCase();
      const isInactive = ['0', 'false', 'inactive'].includes(normalized);
      const variant = isInactive ? 'danger' : 'success';
      const label = isInactive ? statusLabels.inactive : statusLabels.active;
      return gridjs.html(`<span class="badge" data-variant="${variant}">${label}</span>`);
    };
    const gridOptions = {
      gridjs: window.gridjs,
      container: '#departments-grid',
      dataUrl: 'admin/departments/data',
      appBase,
      columns: [
        { name: labels.description || 'Description', sort: true },
        {
          name: labels.status || 'Status',
          sort: false,
          formatter: (cell) => formatStatus(cell),
        },
        { name: labels.code || 'Code', sort: true },
        { name: labels.costCenter || 'Cost center', sort: true },
        {
          name: labels.activeUsers || 'Active users',
          sort: false,
          formatter: (cell) => formatCount(cell),
        },
        {
          name: labels.inactiveUsers || 'Inactive users',
          sort: false,
          formatter: (cell) => formatCount(cell),
        },
        {
          name: labels.created || 'Created',
          sort: true,
          formatter: (cell) => formatBadge(cell),
        },
        {
          name: labels.modified || 'Modified',
          sort: true,
          formatter: (cell) => formatBadge(cell),
        },
        {
          name: 'UUID',
          hidden: true,
        },
      ],
      sortColumns: ['description', null, 'code', 'cost_center', null, null, 'created', 'modified', null],
      paginationLimit: 10,
      language: config.gridLang ?? {},
      mapData: (data) => data.data.map((row) => [
        row.description,
        row.active,
        row.code,
        row.cost_center,
        row.active_users ?? 0,
        row.inactive_users ?? 0,
        row.created,
        row.modified,
        row.uuid,
      ]),
      actions: { enabled: false },
      search: gridSearch,
      filterSchema,
      urlSync: true,
      rowDataset: (row) => ({
        uuid: row?.cells?.[8]?.data,
      }),
      rowDblClick: {
        getUrl: (rowData) => {
          const uuid = rowData?.cells?.[8]?.data;
          return uuid ? new URL(`admin/departments/edit/${uuid}`, appBase).toString() : '';
        },
      },
    };

    const { gridConfig } = initStandardListPage({
      grid: gridOptions,
      filters: {
        mode: 'drawer',
        chipMeta: filterChipMeta,
        watchInputs: ['#department-search'],
        preserveFilterParamsOnReset: ['tenant'],
        drawer: {
          countExcludeParams: ['tenant'],
        },
        clearMetaOptions: {
          preserveFilterParams: ['tenant'],
        },
      },
    });
    if (!gridConfig || !gridConfig.grid) {
      warnOnce('UI_INIT_FAIL', 'Departments grid init failed', { module: 'admin-departments-index', component: 'grid' });
      return null;
    }
    return gridConfig;
  };

  initDepartmentsGrid();
}
