import React, { useRef, useEffect, forwardRef } from 'react';
import { Box, Input, InputProps } from '@wix/design-system';
import { TextOverflowState } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';
import { st, classes } from './InputOverflow.st.css.js';

export interface InputOverflowProps extends InputProps {
  state: TextOverflowState;
  text: string;
  selected: boolean;
  focused: boolean;
}

export const InputOverflow = observer(
  forwardRef((props: InputOverflowProps, ref) => {
    const { state, selected, focused, text, ...inputProps } = props;
    const helperNodeRef = useRef<HTMLInputElement | null>();

    useEffect(() => {
      if (!helperNodeRef.current) {
        return;
      }

      return state.init(helperNodeRef.current);
    }, []);

    return (
      <Box position="relative" direction="vertical">
        <div
          style={{
            height: 0,
            visibility: 'hidden',
          }}
          aria-hidden
        >
          <Input
            {...inputProps}
            ref={ref}
            textOverflow={undefined}
            clearButton={false}
            onClear={undefined}
            value={text}
            inputRef={(node) => {
              helperNodeRef.current = node;
            }}
          />
        </div>
        <Input
          {...inputProps}
          ref={ref}
          onKeyDown={(e) => {
            if (
              e.nativeEvent.code === 'Space' &&
              document.querySelectorAll('[data-option-hovered]').length === 0
            ) {
              e.stopPropagation();
            }

            inputProps.onKeyDown?.(e);
          }}
          textOverflow={undefined}
          className={st(classes.root, {
            selected,
            focused,
          })}
        />
      </Box>
    );
  }),
);
