import { CustomField, CustomFieldType, FiltersMap } from '@wix/bex-core';
import { ToolbarCollectionState } from '../../state';
import React from 'react';
import { DateCustomFieldFilter } from './DateCustomFieldFilter';
import { DateTimeCustomFieldFilter } from './DateTimeCustomFieldFilter';
import { FilterProps } from '../../model';
import { CheckboxCustomFieldFilter } from './CheckboxCustomFieldFilter';
import { NumberRangeFilter } from '../NumberRangeFilter';
import { OperatorFilterCustomFieldFilter } from './OperatorFilterCustomFieldFilter';
import { toFieldType } from '../../utils/fieldTypePrefixIcons';

export const buildCustomFieldFilterElement = <T, F extends FiltersMap>(
  state: ToolbarCollectionState<T, F>,
  customField: CustomField,
) => {
  const customFieldFilterComponents: {
    [key in CustomFieldType]?: React.ComponentType<FilterProps<any>>;
  } = {
    date: DateCustomFieldFilter,
    dateTime: DateTimeCustomFieldFilter,
    checkbox: CheckboxCustomFieldFilter,
    integer: NumberRangeFilter,
    decimal: (props) => <NumberRangeFilter {...props} decimal />,
    shortText: OperatorFilterCustomFieldFilter,
    url: OperatorFilterCustomFieldFilter,
    longText: OperatorFilterCustomFieldFilter,
  };

  const CustomFieldFilterComponent =
    customFieldFilterComponents[customField.type];

  if (!CustomFieldFilterComponent) {
    return null;
  }

  const label = customField.label || customField.id;

  return (
    <CustomFieldFilterComponent
      key={customField.id}
      filter={state.collection.filters[customField.id]!}
      fieldType={toFieldType(customField.type)}
      accordionItemProps={{
        label,
      }}
      toolbarItemProps={{
        label,
      }}
      toolbarTagProps={{
        label,
      }}
    />
  );
};
