import { isEmptyStringOrNotDefined } from '@/helpers/string.helper';
import { Filter, Sort, TableHeader } from '@/models';

/**
 * convert BmsTableFilters filters in readable query parameters
 * use by the team BMS api (bms, contribution, api device)
 * compatible with APIPaginatedResource in use in bo BMS
 * @param params
 */
export const getFiltersAsQueryParams = (params: {
  page: number;
  size: number;
  search: string;
  filters?: Filter[];
  others?: any;
  sort?: Sort;
}) => {
  if (!params) {
    return {
      size: 0,
      page: 0,
    };
  }
  //reset searchParams
  let searchParams = {
    size: params.size,
    page: params.page,
  } as any;
  if (params.others) {
    searchParams = {
      ...searchParams,
      ...params.others,
    };
  }
  if (params.search) {
    searchParams['search'] = params.search;
  }
  if (params.filters) {
    params.filters.forEach((filter: Filter) => {
      try {
        if (filter.value !== null && filter.value !== '') {
          searchParams[filter.key] = filter.value;
        }
        if (
          ['betweenDate', 'betweenDateTime', 'betweenNumber'].includes(
            filter.type,
          )
        ) {
          if (!isEmptyStringOrNotDefined(filter.valueFrom)) {
            if (filter.type === 'betweenDate') {
              searchParams[`${filter.key}From`] = new Date(
                filter.valueFrom,
              ).toISOString();
            } else {
              searchParams[`${filter.key}From`] = filter.valueFrom;
            }
          }
          if (!isEmptyStringOrNotDefined(filter.valueTo)) {
            if (filter.type === 'betweenDate') {
              const dateTo = new Date(filter.valueTo);
              dateTo.setHours(25, 59, 59, 0); // for local purpose (GMT+2)
              searchParams[`${filter.key}To`] = dateTo.toISOString();
            } else {
              searchParams[`${filter.key}To`] = filter.valueTo;
            }
          }
        }
      } catch (e: any) {
        console.error(e);
      }
    });
  }
  return searchParams;
};

export const enforceActionsColumnHeader = (
  headers: TableHeader[],
): TableHeader[] => {
  const actionsHeaders = headers
    .filter((h) => h.action)
    .map((h) => ({ ...h, width: h.width ?? '75px' }))
    .map((h) => ({ ...h, align: h.align ?? 'center' }));
  if (actionsHeaders.length > 1)
    console.error('Table component cannot have multiple action columns ');
  return headers
    .filter((h) => !h?.action)
    .concat(actionsHeaders.length ? actionsHeaders[0] : []);
};

const getAlignClass = (header: TableHeader) => {
  const align = !header.align ? 'start' : header.align;
  return `u-text-align-${align}`;
};

export const getHeaderClasses = (header: TableHeader, sort: Sort): string[] => {
  const classes = [getAlignClass(header), 'bms-table__header-cell'];
  if (header.class) {
    classes.push(header.class);
  }
  if (header.sortable) {
    classes.push('sortable');
  }
  if (sort.key === header.key) {
    classes.push('sorted');
  }
  return classes;
};
