import React, { useRef, useState } from "react";
import { InputProps } from "../../data/Props";
import { CommonTitle } from "../title/CommonTitle";
import InputStyle from "./input.module.css";

export function LimitInput(props: InputProps) {
  const [curLength, setLength] = useState<number>(0);
  const compositionRef = useRef<boolean>(true);
  const inputRef = useRef<HTMLTextAreaElement>(null);

  const handleTextChange = () => {
    if (compositionRef.current) {
      const length = inputRef?.current?.value?.length;
      setLength(length ?? 0);
      if (typeof props?.onTextChanged === "function") {
        props?.onTextChanged(inputRef?.current?.value ?? "");
      }
    }
  };

  const handleComposition = (
    event: React.CompositionEvent<HTMLTextAreaElement>
  ) => {
    if ("compositionend" === event.type) {
      compositionRef.current = true;
      handleTextChange();
    } else {
      compositionRef.current = false;
    }
  };

  return (
    <div style={props?.styles}>
      {props?.title ? (
        <CommonTitle title={props.title} must={props.must}></CommonTitle>
      ) : null}
      <div className={InputStyle.container}>
        <textarea
          ref={inputRef}
          className={InputStyle.input}
          placeholder={props?.inputHint}
          maxLength={props?.maxLength}
          onChange={handleTextChange}
          onCompositionStart={handleComposition}
          onCompositionEnd={handleComposition}
          onCompositionUpdate={handleComposition}
        ></textarea>
        {props.maxLength ? (
          <p className={InputStyle.limit}>
            <span
              style={{
                color: curLength === props?.maxLength ? "#F27724" : "#666",
                fontSize: "12px",
              }}
            >
              {curLength}
            </span>
            <span style={{ color: "#999", fontSize: "12px" }}>
              /{props?.maxLength}
            </span>
          </p>
        ) : null}
      </div>
      {props?.tip ? <div className={InputStyle.tip}>{props?.tip}</div> : null}
    </div>
  );
}
