import React, { useCallback, useRef } from 'react';
import { clsx } from 'clsx';

import { useCombinedRef, useIsFocused } from '../utils/hooks';
import { forwardRef } from '../utils/react';
import { InputContainer, InputContainerProps } from '../input-container';
import * as css from './input.css';

/*-- Types --*/

export interface InputProps extends InputContainerProps {}

/*-- Main --*/

export const Input = forwardRef<'input', InputProps>(function Input(
  {
    startAddon,
    startAddonProps,
    endAddon,
    endAddonProps,
    startAddonRef,
    endAddonRef,
    onFocus: userOnFocus,
    onBlur: userOnBlur,
    disabled,
    full,
    className,
    ...rest
  },
  ref,
) {
  const inputRef = useRef<HTMLInputElement>(null);
  const combinedInputRef = useCombinedRef(ref, inputRef);

  const { isFocused, onFocus, onBlur } = useIsFocused({
    onFocus: userOnFocus,
    onBlur: userOnBlur,
  });

  const onContainerClick: React.MouseEventHandler<HTMLDivElement> = useCallback(
    event => {
      if (inputRef.current && event.currentTarget === event.target) {
        inputRef.current.focus();
      }
    },
    [],
  );

  const inputCn = clsx(className, css.input);

  return (
    <InputContainer
      focused={isFocused}
      disabled={disabled}
      full={full}
      onClick={onContainerClick}
      startAddon={startAddon}
      startAddonProps={startAddonProps}
      endAddon={endAddon}
      endAddonProps={endAddonProps}
      startAddonRef={startAddonRef}
      endAddonRef={endAddonRef}
    >
      <input
        {...rest}
        ref={combinedInputRef}
        className={inputCn}
        onFocus={onFocus}
        onBlur={onBlur}
        disabled={disabled}
      />
    </InputContainer>
  );
});
