import { createListPageModule } from '../core/app-list-page-module.js';
import { badgeHtml } from './app-list-utils.js';

createListPageModule({
  configId: 'admin-departments-index',
  moduleId: 'admin-departments-index',
  missingGridMessage: 'Departments grid init failed: Grid.js missing',
  initErrorMessage: 'Departments grid init failed',
  setup: ({ config, gridjs, appBase, initListPage }) => {
    const gridSearch = config.gridSearch ?? null;
    const filterSchema = config.filterSchema ?? [];
    const filterChipMeta = config.filterChipMeta ?? [];
    const labels = config.labels ?? {};

    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 { gridConfig } = initListPage({
      grid: {
        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,
        ]),
        rowInteraction: { linkColumn: 0 },
        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() : '';
          },
        },
      },
      filters: {
        mode: 'drawer',
        chipMeta: filterChipMeta,
        watchInputs: ['#department-search'],
        preserveFilterParamsOnReset: ['tenant'],
        drawer: {
          countExcludeParams: ['tenant'],
        },
        clearMetaOptions: {
          preserveFilterParams: ['tenant'],
        },
      },
    }) || {};

    return gridConfig;
  },
});
