import React, { FC, RefObject, useEffect, useState } from 'react';

import css from './index.module.css';
import classNames from 'classnames';

export interface TextareaProps {
  inputRef?: RefObject<HTMLTextAreaElement>;
  label?: string;
  value?: string;
  required?: boolean;
  placeholder?: string;
  name?: string;
  onChange?: (e) => void;
  initialRows?: number;
  style?: 'normal' | 'booking';
  optional: boolean;
  isKeyBoardOpen?: (e) => void;
}

const Textarea: FC<TextareaProps> = ({
  inputRef,
  label,
  value,
  required,
  placeholder,
  onChange,
  name,
  initialRows,
  style = 'normal',
  optional = false,
  isKeyBoardOpen,
}) => {
  const [isActive, setActive] = useState(false);
  const textareaClassNames = classNames(css.textarea, {
    [css.textarea__booking]: style === 'booking',
    [css.textarea__active]: isActive,
  });

  const [rows, setRows] = useState(initialRows ? initialRows : 5);
  const minRows = initialRows;
  const maxRows = 10;

  const handleChange = (event): void => {
    setActive(true);
    const textareaLineHeight = 24;

    const previousRows = event.target.rows;
    event.target.rows = minRows; // reset number of rows in textarea

    const currentRows = ~~(event.target.scrollHeight / textareaLineHeight);

    if (currentRows === previousRows) {
      event.target.rows = currentRows;
    }

    if (currentRows >= maxRows) {
      event.target.rows = maxRows;
      event.target.scrollTop = event.target.scrollHeight;
    }
    setRows(currentRows < maxRows ? currentRows : maxRows);

    if (onChange) onChange(event);
  };

  useEffect(() => {
    setActive(value !== undefined && value != '');
  }, [value]);

  const disableFocus = (e): void => {
    if (e.target.value === '') {
      setActive(false);
    }
  };

  return (
    <>
      <label className={textareaClassNames}>
        <span className={css.textarea__label}>
          {isActive ? label : placeholder ? placeholder : label}
        </span>
        <textarea
          onBlur={(e: React.FocusEvent<HTMLTextAreaElement>): void => {
            disableFocus(e);
            if (isKeyBoardOpen) isKeyBoardOpen(false);
          }}
          onFocus={(): void => {
            setActive(true);
            if (isKeyBoardOpen) isKeyBoardOpen(true);
          }}
          rows={rows}
          onChange={handleChange}
          name={name}
          className={css.textarea__input}
          ref={inputRef}
          value={value}
          required={required}
        />
      </label>
      {optional && <span className={css.textarea__optional}>Optional</span>}
    </>
  );
};

export default Textarea;
