import React from 'react';

import './input.css';

export type Props = {
  placeholder: string;
  maxLength?: number;
  type: 'text' | 'password';
  value: string;
  className?: string;
  inputMode?: 'numeric';
  floatingPlaceholder?: boolean;
  onChange: (value: string) => void;
  onFocus?: (event: React.FocusEvent) => void;
  onBlur?: (value: React.FocusEvent) => void;
};

export default function Input(props: Props) {
  const [isFocused, setIsFocused] = React.useState(false);

  const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    props.onChange(event.target.value);
  };

  const onBlur = (event: React.FocusEvent) => {
    setIsFocused(false);

    if (props.onBlur) {
      props.onBlur(event);
    }
  }

  const onFocus = (event: React.FocusEvent) => {
    setIsFocused(true);

    if (props.onFocus) {
      props.onFocus(event);
    }
  };

  const className = ['input'];

  if (props.value) {
    className.push('input_filled');
  }

  if (props.className) {
    className.push(props.className);
  }

  if (props.floatingPlaceholder) {
    className.push('input_floating-placeholder');
  }

  return (
    <label className={className.join(' ')}>
      <input
        type={props.type}
        placeholder=" "
        maxLength={props.maxLength}
        value={props.value}
        inputMode={props.inputMode}
        onChange={onChange}
        onFocus={onFocus}
        onBlur={onBlur}
      />

      {!props.value && !isFocused && <p className="input__placeholder">{props.placeholder}</p>}

      <div className="input__icon-wrapper"/>
    </label>
  );
}
