import React, {
  ChangeEvent,
  useEffect,
  useRef,
  useState,
} from 'react';

import {COLOR, Date} from '@propellerads/icon';
import InputText from '@propellerads/input-text';

import {getFormattedValue} from '../helpers';
import {DatePickerControlsProps} from '../types';

import {DateIcon, DatePickerControlsFields} from './style';

const KEY_ENTER = 'Enter';

const DatePickerControls = ({
  elementId,
  placeholder,
  onStartChange,
  value,
  dateFormat,
  onChange,
  onEndChange,
  regMask = /^(([0-9]{0,2}[/]?)|([0-9]{0,2}[/][0-9]{0,2}\/?)|([0-9]{0,2}[/]){2}[0-9]{0,4})$/,
}: DatePickerControlsProps) => {
  const [inputValue, setValue] = useState<string>('');
  const [cursorPosition, setCursorPosition] = useState(-1);
  const [isFocused, setFocused] = useState(false);
  const dateRef = useRef<HTMLDivElement>();

  const onFocus = () => {
    onStartChange();
    setFocused(true);
  };

  const onBlur = () => {
    setFocused(false);
  };

  const onKeyDown = (event: KeyboardEvent) => {
    if (event.key === KEY_ENTER) {
      onEndChange(inputValue);

      const test = event.target as HTMLInputElement;

      test.blur();
      event.preventDefault();
    }
  };

  const onChangeInputMask = (targetValue: string, event: ChangeEvent<HTMLInputElement>) => {
    if (regMask.test(targetValue)) {
      setValue(targetValue);

      onChange(targetValue);
    }

    setCursorPosition(Number(event.target.selectionStart));
  };

  useEffect(() => {
    if (cursorPosition !== -1) {
      const inputElement: HTMLInputElement = document.getElementById(`${elementId}-input`) as HTMLInputElement;
      inputElement?.setSelectionRange(cursorPosition, cursorPosition);
      setCursorPosition(-1);
    }
  }, [cursorPosition]);

  useEffect(() => {
    setValue(getFormattedValue(value, dateFormat));
  }, [value, isFocused]);

  return (
    <DatePickerControlsFields>
      <DateIcon>
        <Date color={COLOR.GRAY} />
      </DateIcon>

      <InputText
        onFocus={onFocus}
        elementId={`${elementId}-input`}
        name="single-datepicker-input"
        value={inputValue}
        inputRef={dateRef}
        placeholder={placeholder}
        onChange={onChangeInputMask}
        onKeyPress={onKeyDown}
        onBlur={onBlur}
      />
    </DatePickerControlsFields>
  );
};

export default DatePickerControls;
