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

import InputText from "@/components/quiz-section/input-text";
import LabelInput from "@/components/quiz-section/label-input";
import Object3dBounds from "@/components/quiz-section/object3d-bounds";
import { getCopy } from "@/config/copy";
import { QUIZ_STEPS, QUIZ_STEPS_VARIANTS } from "@/config/data";
import { useStore } from "@/store";

import parentStyles from "../styles.module.scss";

const QuestionToSection = ({
  label,
  placeholder,
  setButtonState,
  clickButton,
}: {
  label: string;
  placeholder: string;
  setButtonState: (state: boolean) => void;
  clickButton: () => void;
}) => {
  const step = useStore.use.step();
  const nameTo = useStore.use.nameTo();
  const setNameTo = useStore.use.setNameTo();
  const errorWarning = useStore.use.errorWarning();
  const setErrorWarning = useStore.use.setErrorWarning();
  const showErrorWarning = useStore.use.showErrorWarning();

  const inputRef = useRef(null);

  const isCurrentStep =
    QUIZ_STEPS[step]?.id === QUIZ_STEPS_VARIANTS["question-to"];

  useEffect(() => {
    if (isCurrentStep) {
      (inputRef.current as any).validateInput(nameTo, true);
    } else {
      (inputRef.current as any).removeFocus();
    }
  }, [isCurrentStep, nameTo]);

  return (
    <div className={parentStyles.fieldText}>
      <Object3dBounds />
      <LabelInput label={label} ariaHidden={!isCurrentStep || undefined} />
      <InputText
        ref={inputRef}
        placeholder={placeholder}
        type="name"
        value={nameTo}
        ariaLabel={label}
        tabIndex={isCurrentStep ? 0 : -1}
        ariaHidden={!isCurrentStep || undefined}
        onChange={(text) => setNameTo(text)}
        onValidate={(ok: boolean) => setButtonState(ok)}
        onError={(error: string, input: HTMLInputElement) => {
          setErrorWarning({ message: getCopy("sign:error"), input: input });
        }}
        onEnterKey={clickButton}
      />
    </div>
  );
};

export default QuestionToSection;
