import React, { useEffect } from 'react';
import { observer } from 'mobx-react-lite';
import {
  Box,
  DropdownBase,
  Input,
  FormField,
  listItemSelectBuilder,
  TextButton,
} from '@wix/design-system';
import {
  FilterOperator,
  OperatorFilterValue,
  getOperatorLabel,
} from '@wix/bex-core';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { useOperatorFilterState } from '../../hooks/useOperatorFilterState';
import { FilterProps } from '../../model';
import { ChevronDown } from '@wix/wix-ui-icons-common';

export interface OperatorPickerProps<T>
  extends FilterProps<OperatorFilterValue<T>> {
  /**
   * List of allowed operators for this filter
   * @external
   */
  allowedOperators: FilterOperator[];
}

function _OperatorFilterPicker<T>(props: OperatorPickerProps<T>) {
  const { filter, allowedOperators } = props;
  const { translate: t } = useWixPatternsContainer();

  const state = useOperatorFilterState<T>({
    filter,
    allowedOperators,
  });

  useEffect(() => state.init(), [state]);

  const operatorOptions = allowedOperators.map((op) =>
    listItemSelectBuilder({
      id: op,
      title: t(getOperatorLabel(op)),
      label: t(getOperatorLabel(op)),
    }),
  );

  const showValueInput = state.operatorNeedsValue();

  return (
    <Box
      dataHook={`operator-picker-${filter.name}`}
      direction="vertical"
      gap="12px"
    >
      <FormField>
        <DropdownBase
          options={operatorOptions}
          selectedId={state.operator}
          onSelect={(option) => state.setOperator(option.id as FilterOperator)}
          dataHook="operator-picker-operator-dropdown"
        >
          {({ toggle }) => (
            <TextButton
              skin="dark"
              onClick={toggle}
              suffixIcon={<ChevronDown />}
              size="small"
              dataHook="operator-picker-trigger"
            >
              {t(getOperatorLabel(state.operator))}
            </TextButton>
          )}
        </DropdownBase>
      </FormField>

      {showValueInput && (
        <FormField>
          <Input
            border={'round'}
            value={state.value?.toString() || ''}
            placeholder={t('cairo.filterOperator.valuePlaceholder')}
            onChange={(e) => state.setValue(e.target.value as T)}
            onBlur={() => state.applyImmediately()}
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                state.applyImmediately();
              }
            }}
            dataHook="operator-picker-value-input"
          />
        </FormField>
      )}
    </Box>
  );
}

export const OperatorFilterPicker = observer(_OperatorFilterPicker);
