import { AutoComplete, AutoCompleteProps, Input } from '@wix/design-system';
import React, { useEffect, useMemo, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { AutoCompleteReadonlyState } from './AutoCompleteReadonlyState';
import { classes, st } from './AutoCompleteReadonly.st.css.js';

export interface AutoCompleteReadonlyProps extends AutoCompleteProps {
  selectedLabel?: string;
  state?: AutoCompleteReadonlyState;
  clearInput?: () => void;
}

function _AutoCompleteReadonly(props: AutoCompleteReadonlyProps) {
  const { value, selectedLabel, dropdownWidth, clearInput } = props;

  const [state] = useState(
    () => props.state ?? new AutoCompleteReadonlyState(),
  );

  useEffect(() => {
    state.clearInput = clearInput;
  }, [clearInput]);

  const { disableEditing } = state;

  const valueOrSelected = useMemo(() => {
    return disableEditing ? selectedLabel || '' : value;
  }, [value, disableEditing, selectedLabel]);

  return (
    <AutoComplete
      {...props}
      dropdownWidth={dropdownWidth}
      onSelect={(option, sameOptionWasPicked) => {
        props.onSelect?.(option, sameOptionWasPicked);
        state.onSelect();
      }}
      onFocus={state.onFocus}
      onBlur={(e) => {
        props.onBlur?.(e);
        state.onBlur();
      }}
      onClickOutside={(e) => {
        props.onClickOutside?.(e);
        state.onClickOutside();
      }}
      suffix={
        !disableEditing && String(value)?.trim() ? undefined : props.suffix
      }
      placeholder={
        !disableEditing && selectedLabel != null
          ? String(selectedLabel)
          : props.placeholder
      }
      onKeyDown={(e) => {
        if (e.nativeEvent.code === 'Tab') {
          state.onTabKeyDown();
        }
      }}
      clearButton={!disableEditing}
      onClear={
        !disableEditing
          ? (e) => {
              props.onClear?.(e);
              state.onInputClearButtonClick();
            }
          : undefined
      }
      value={valueOrSelected}
      onOptionsShow={state.onOptionsShow}
      focusOnClearClick
      className={st(classes.root, {
        disableEditing,
      })}
      inputElement={<Input disableEditing={disableEditing} />}
    />
  );
}

export const AutoCompleteReadonly = observer(_AutoCompleteReadonly);
