import { useEffect, useRef, useState } from 'react';
import { v4 } from 'uuid';
import Keyboard from '../keyboard/Keyboard';

export default function Input(props: {
  type?: string;
  topKeyboard?: boolean;
  value: any;
  min?: number;
  max?: number;
  step?: number;
  placeholder?: any;
  className?: string;
  disabled?: boolean;
  onChange?: (value: string) => void;
  onBlur?: (value: string) => void;
}) {
  const [guid] = useState(v4());
  const ref = useRef<HTMLInputElement>(null);
  const keyboardRef = useRef<HTMLDivElement>(null);
  const blurRef = useRef<boolean>(false);
  const [isFocused, setFocused] = useState(false);
  const [showKeyboard, setShowKeyboard] = useState(false);

  useEffect(() => {
    if (isFocused) {
      Coherent.trigger('FOCUS_INPUT_FIELD', guid, '', '', '', false);
    } else {
      console.log('UNFOCUS_INPUT_FIELD');
      Coherent.trigger('UNFOCUS_INPUT_FIELD', guid);
    }
  }, [isFocused, guid]);

  return (
    <>
      <input
        ref={ref}
        type={props.type ? props.type : 'text'}
        min={props.min}
        max={props.max}
        step={props.step}
        placeholder={props.placeholder}
        disabled={props.disabled}
        onFocus={() => {
          if (!isFocused) {
            setFocused(true);
            setShowKeyboard(true);
            ref.current?.select();
          }
        }}
        onBlur={(e) => {
          if (blurRef.current && isFocused) ref.current?.focus();
          else {
            props.onBlur?.(e.target.value);
            setShowKeyboard(false);
            setFocused(false);
            ref.current?.blur();
          }
          blurRef.current = false;
        }}
        onChange={(e) => {
          if (props.onChange) props.onChange(e.target.value);
        }}
        value={props.value}
        className={props.className}
      />
      {showKeyboard && (
        <Keyboard
          ref={keyboardRef}
          top={props.topKeyboard}
          value={String(props.value)}
          blurRef={blurRef}
          onInput={(value) => props.onChange && props.onChange(value)}
          onClose={() => {
            setShowKeyboard(false);
            setFocused(false);
            ref.current?.blur();
          }}
        />
      )}
    </>
  );
}
