// @flow
import React, { useState, useEffect } from 'react';
import styled from 'styled-components';

import { FormInput } from '../../form-input';
import { SelectorItem } from '../selector-item';

import {
  type SelectorItemWithInputProps,
  selectorItemWithInputProptypes,
} from './selector-item.proptypes';
import { ErrorLabel } from '../../forms.common';
import { Box } from '../../../../primitives/box';

const StyledFormInput = styled(FormInput)`
  background: none;
  width: 100%;
  padding-left: 0;
  font-weight: 900;
  font-size: 18px;

  &,
  &:focus {
    border: none;
  }
`;

export const SelectorItemWithInput = ({
  onInputChange,
  inputValue,
  inputProps,
  inputError,
  ...props
}: SelectorItemWithInputProps) => {
  const [textInputRef, setTextInputRef] = useState(null);
  const [selectorRef, setSelectorRef] = useState(null);
  const errorString = (typeof inputError === 'string' ||
    (typeof inputError === 'object' && inputError != null)) && (
    <ErrorLabel>{inputError}</ErrorLabel>
  );

  useEffect(() => {
    if (selectorRef != null && textInputRef != null) {
      selectorRef.onclick = () => textInputRef.focus();
    }
  }, [selectorRef, textInputRef]);

  return (
    <SelectorItem
      {...{
        ...props,
        onRef: setSelectorRef,
      }}
    >
      <Box stacked="column">
        <StyledFormInput
          {...inputProps}
          tabIndex="-1"
          onChange={onInputChange}
          value={inputValue}
          onRef={setTextInputRef}
        />
        {errorString}
      </Box>
    </SelectorItem>
  );
};

SelectorItemWithInput.displayName = 'SelectorItemWithInput';
SelectorItemWithInput.propTypes = selectorItemWithInputProptypes;
