import { useState, useEffect, HTMLAttributes } from "react";

import "./FormField.css";
import { getCN, randomId, clickDetective } from "../../components/utils";

export interface IFormField extends HTMLAttributes<HTMLDivElement> {
  status?: `default` | `error` | `valid`;
  hovered?: `default` | `input`;
  before?: React.ReactNode;
  after?: React.ReactNode;
  top?: React.ReactNode;
  bottom?: React.ReactNode;
  onActive?: (status?: boolean) => void;
  formClassName?: string | undefined;
}

function FormField({
  children,
  before,
  after,
  top,
  status = `default`,
  bottom,
  hovered = `default`,
  onActive,
  formClassName,
  ...props
}: IFormField) {
  const [props_id, setPropsId] = useState(randomId(props.id, `formItem`));

  const [is_mobile_hover, setMobileHover] = useState(false);
  const [is_hover, setHover] = useState(false);
  const [is_active, setActive] = useState(false);

  const onMouseHover = (e: any) => {
    if (!is_mobile_hover) {
      if (e.type == "mouseover") {
        setHover(true);
        if (props.onMouseOver) props.onMouseOver(e);
      } else if (e.type == "mouseout") {
        setHover(false);
        if (props.onMouseOut) props.onMouseOut(e);
      }
    }
  };

  const onBlur = (e: any) => {
    setHover(false);
    setActive(false);
    if (onActive) onActive(false);
  };

  const onFocus = (e: any) => {
    setActive(true);
    if (onActive) onActive(true);
  };

  const onTouchStart = (e: any) => {
    setMobileHover(true);
    if (props.onTouchStart) props.onTouchStart(e);
  };

  return (
    <div
      className={getCN(
        ["MYUI-FormField", `MYUI-FormField--${status}`],
        props.className
      )}
    >
      {top && <div className="MYUI-FormField__top">{top}</div>}
      <div
        onTouchStart={onTouchStart}
        onMouseOver={onMouseHover}
        onMouseOut={onMouseHover}
        onFocus={onFocus}
        onBlur={onBlur}
        id={props_id}
        {...props}
        className={getCN(
          [
            "MYUI-FormField__in",
            hovered == `input` && is_hover && `MYUI-FormField__hover`,
            hovered == `input` && is_active && `MYUI-FormField__active`,
          ],
          formClassName
        )}
      >
        {before && <div className="MYUI-FormField__before">{before}</div>}
        {children}
        {after && <div className="MYUI-FormField__after">{after}</div>}
      </div>
      {bottom && <div className="MYUI-FormField__bottom">{bottom}</div>}
    </div>
  );
}

export default FormField;
