import { useEffect, useRef, useState } from "react";
import styles from "../../styles/room/input.module.scss";
import { parseClassName } from "../../utils/utils.js";

export default function InputExo({ isCorr, idInput, inputData, idExo, idCalcul }) {
  const [result, setResult] = useState({
    enter: inputData.value,
    correction: inputData.correction,
    isCorrect: inputData.correction == "" ? null : false,
  });
  const ref = useRef();
  const span = useRef();
  const [width, setWidth] = useState(50);
  useEffect(() => {
    if (span.current) {
      setWidth(span.current.offsetWidth);
    }
  }, [result.enter]);
  useEffect(() => {{
    if(isCorr == true)
    setResult({
      ...result,
      correction: inputData.correction, 
      isCorrect: inputData.correction == "" ? null : (inputData.correction == result.enter),
    });}
  }, [isCorr, inputData])
  return (
    <>
      <input
        ref={ref}
        type="text"
        value={result.enter}
        className={parseClassName([
          styles["input"],
          isCorr
            ? result.isCorrect
              ? styles["valid"]
              : styles["invalid"]
            : undefined,
          isCorr ? styles["disabled"] : undefined,
          isCorr
            ? result.correction == ""
              ? styles["withoutCorrection"]
              : undefined
            : undefined,
        ])}
        onChange={(e) => {
          setResult({
            ...result,
            enter: e.target.value,
            isCorrect:
              result.correction != ""
                ? result.correction == e.target.value
                : null,
          });
        }}
        // data-correct={isCorr ? result.isCorrect : undefined}
        //data-correction={isCorr ? corr : undefined}
        //data-calcul={isCorr ? calcul: undefined}
        data-idexo={idExo}
        data-idinput={idInput}
        data-idcalcul={idCalcul}
        disabled={isCorr}
        style={{
          ...(span.current && { width: span.current.offsetWidth + "px" }),
        }}
      />
      <span className={styles.span} ref={span}>
        {result.enter.replace(/\s/g, "&nbsp;")}
      </span>
    </>
  );
}
