import {
  CustomField,
  CustomFieldType,
  FiltersMap,
  STRING_OPERATORS,
} 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 { OperatorFilterPicker } from '../OperatorFilterPicker';

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: ({ filter }) => <NumberRangeFilter filter={filter} decimal />,
    shortText: ({ filter }) => (
      <OperatorFilterPicker
        filter={filter}
        allowedOperators={STRING_OPERATORS}
      />
    ),
    url: ({ filter }) => (
      <OperatorFilterPicker
        filter={filter}
        allowedOperators={STRING_OPERATORS}
      />
    ),
    longText: ({ filter }) => (
      <OperatorFilterPicker
        filter={filter}
        allowedOperators={STRING_OPERATORS}
      />
    ),
  };

  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]!}
      accordionItemProps={{
        label,
      }}
      toolbarItemProps={{
        label,
      }}
    />
  );
};
