import React, { FormEvent, forwardRef, RefObject, useEffect } from "react";
import { Box } from "../../Box";
import { ICON_TYPE } from "../../Icon";
import { Input, INPUT_ICON_POSITION } from "../../Input";

interface SelectSearchProps {
  value: string | undefined;
  onChange: (e: FormEvent<HTMLInputElement>) => void;
  setInputHasFocus: (newVal: boolean) => void;
  popperRef: RefObject<HTMLDivElement>;
}

export const SelectSearch = forwardRef<HTMLInputElement, SelectSearchProps>(
  (
    { value, onChange, setInputHasFocus, popperRef }: SelectSearchProps,
    ref,
  ) => {
    useEffect(() => {
      // make copies of refs for use in the callback
      const inputRef = ref;
      const popperRefCopy = popperRef;

      return () => {
        // Set focus to false since onBlur might not get called when unmounting
        setInputHasFocus(false);

        // If the input was still focused when unmounting this component, then we
        // should redirect focus to the menu (aka popper). This is what downshift
        // would have done if this were a regular select item.
        if (
          inputRef &&
          "current" in inputRef &&
          popperRefCopy &&
          popperRefCopy.current
        ) {
          if (inputRef.current === document.activeElement) {
            popperRefCopy.current.focus();
          }
        }
      };
    }, [setInputHasFocus, ref, popperRef]);

    return (
      <Box className="p-3 border-b sticky top-0 w-full bg-white z-10" as="li">
        <Input
          ref={ref}
          type="text"
          icon={ICON_TYPE.SEARCH}
          iconPosition={INPUT_ICON_POSITION.RIGHT}
          value={value}
          onChange={onChange}
          onFocus={() => {
            setInputHasFocus(true);
          }}
          onBlur={() => {
            setInputHasFocus(false);
          }}
        />
      </Box>
    );
  },
);
