import {
  FilterItem,
  MAP_DATE_PRESET_TO_KEY,
  presetToDaysAmount,
  RangeItem,
  Translate,
} from '@wix/bex-core';
import { createElement } from 'react';
import { FilterProps } from '../../model';
import { FilterTagContent } from '../AppliedFiltersTagList/FilterTagContent';

export const renderPresetToolbarTag = (
  container: {
    translate: Translate;
    dateFormatters: {
      medium: Intl.DateTimeFormat;
      mediumTime: Intl.DateTimeFormat;
    };
  },
  params: {
    filterProps: FilterProps<any>;
  },
) => {
  return <V>(filter: FilterItem<V>) => {
    const { filterProps } = params;
    const { translate: t, dateFormatters } = container;
    const { preset } = filter as FilterItem<RangeItem<Date>>;
    if (!preset || !presetToDaysAmount[preset]) {
      return {
        children: createElement(
          FilterTagContent,
          { filterProps },
          getDateRangeLabel(filter as RangeItem<Date>, {
            dateFormatters,
          }),
        ),
      };
    }
    return {
      children: createElement(
        FilterTagContent,
        { filterProps },
        t(MAP_DATE_PRESET_TO_KEY[preset]),
      ),
    };
  };
};

const getDateRangeLabel = (
  item: RangeItem<Date>,
  {
    dateFormatters,
  }: {
    dateFormatters: {
      medium: Intl.DateTimeFormat;
      mediumTime: Intl.DateTimeFormat;
    };
  },
) => {
  return [item.from, item.to]
    .filter(Boolean as unknown as (d: Date | null) => d is Date)
    .map((date) => dateFormatters.mediumTime.format(date))
    .join(' - ');
};
