import {
  AutoComplete,
  AutoCompleteProps,
  Input,
} from '@wix/design-system';
import React, { useEffect, useMemo, useRef, 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 autoCompleteRef = useRef<typeof AutoComplete.prototype | null>(null);

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

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

  const { disableEditing } = state;

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

  return (
    <AutoComplete
      ref={autoCompleteRef}
      {...props}
      dropdownWidth={dropdownWidth}
      onSelect={(option, sameOptionWasPicked) => {
        props.onSelect?.(option, sameOptionWasPicked);
        state.onSelect();
      }}
      onFocus={(e) => {
        state.onFocus();
        props.onFocus?.(e);
      }}
      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);
