import { useEffect, useRef, useState } from "react";
import { useUser } from "@clerk/nextjs";

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

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

const QuestionFromSection = ({
  label,
  placeholder,
  label2,
  placeholder2,
  setButtonState,
  clickButton,
}: {
  label: string;
  placeholder: string;
  label2: string;
  placeholder2: string;
  setButtonState: (state: boolean) => void;
  clickButton: () => void;
}) => {
  const step = useStore.use.step();
  const nameFrom = useStore.use.nameFrom();
  const setNameFrom = useStore.use.setNameFrom();

  const emailFrom = useStore.use.emailFrom();
  const setEmailFrom = useStore.use.setEmailFrom();
  const [setName, setSetName] = useState(false);

  const agreeTC = useStore.use.agreeTC();
  const setAgreeTC = useStore.use.setAgreeTC();

  const { user } = useUser();

  const [nameValidated, setNameValidated] = useState(false);
  const [emailValidated, setEmailValidated] = useState(false);

  const errorWarning = useStore.use.errorWarning();
  const setErrorWarning = useStore.use.setErrorWarning();
  const showErrorWarning = useStore.use.showErrorWarning();

  const inputRef = useRef(null);
  const inputMailRef = useRef(null);
  const checkboxRef = useRef(null);

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

  useEffect(() => {
    if (isCurrentStep) {
      if (!agreeTC) {
        setErrorWarning({
          message: getCopy("sign:error_checkbox"),
          input: this,
        });
      }

      if (!nameFrom && !setName && user?.fullName) {
        setNameFrom(user?.firstName as string);
        setSetName(true);
      }

      if (isCurrentStep) {
        (inputRef.current as any).validateInput(
          nameFrom,
          nameFrom === "" && emailFrom === "",
        );
        (inputMailRef.current as any).validateInput(
          user?.primaryEmailAddress?.emailAddress || emailFrom,
          false,
        );
      } else {
        (inputRef.current as any).removeFocus();
        (inputMailRef.current as any).removeFocus();
      }

      setButtonState(nameValidated && emailValidated && agreeTC);
    }
  }, [
    agreeTC,
    nameFrom,
    setName,
    setSetName,
    emailFrom,
    nameValidated,
    emailValidated,
    isCurrentStep,
  ]);

  return (
    <div
      className={`${styles.quizSection}`}
      aria-hidden={!isCurrentStep || undefined}
    >
      <div>
        <div
          className={`${parentStyles.fieldText} ${styles.fromBlock}`}
          aria-hidden={!isCurrentStep || undefined}
        >
          <LabelInput label={label} ariaHidden={!isCurrentStep || undefined} />
          <InputText
            ref={inputRef}
            type="name"
            placeholder={placeholder}
            value={nameFrom}
            ariaLabel={label}
            tabIndex={isCurrentStep ? 0 : -1}
            ariaHidden={!isCurrentStep || undefined}
            onChange={(text) => setNameFrom(text)}
            onValidate={(ok) => setNameValidated(ok)}
            onError={(error: string, input: HTMLInputElement) =>
              setErrorWarning({
                message: getCopy("sign:error"),
                input: input,
              })
            }
            onEnterKey={clickButton}
          />
        </div>

        <div
          className={`${parentStyles.fieldText} ${styles.emailBlock}`}
          aria-hidden={!isCurrentStep || undefined}
        >
          <LabelInput label={label2} ariaHidden={!isCurrentStep || undefined} />
          <InputText
            ref={inputMailRef}
            type="email"
            placeholder={placeholder2}
            tabIndex={isCurrentStep ? 0 : -1}
            ariaHidden={!isCurrentStep || undefined}
            ariaLabel={label2}
            value={user?.primaryEmailAddress?.emailAddress || emailFrom}
            onChange={(text) => setEmailFrom(text)}
            onValidate={(ok) => setEmailValidated(ok)}
            onError={(error: string, input: HTMLInputElement) => {
              switch (error) {
                case errors.INVALID:
                  setErrorWarning({
                    message: getCopy("sign:error_invalid_email"),
                    input: input,
                  });
                  break;
                default:
                  setErrorWarning({
                    message: getCopy("sign:error"),
                    input: input,
                  });
              }
            }}
            onEnterKey={clickButton}
          />
        </div>

        <div className={styles.legalBlock}>
          <Checkbox
            ref={checkboxRef}
            label={getCopy("sign:checkbox").replace(
              "[LINK]",
              `<a href="https://www.suno.ai/privacy" target="_blank" tabIndex="${isCurrentStep ? "0" : "-1"}">Privacy Policy</a>`,
            )}
            ariaLabel={getCopy("sign:checkbox").replace(
              "[LINK]",
              "Privacy Policy",
            )}
            value={agreeTC}
            tabIndex={isCurrentStep ? 0 : -1}
            ariaHidden={!isCurrentStep || undefined}
            onChange={(value) => setAgreeTC(value)}
          ></Checkbox>
          <p
            className={styles.legalLabel}
            aria-hidden={!isCurrentStep || undefined}
          >
            {getCopy("sign:info")}
          </p>
        </div>
      </div>
    </div>
  );
};

export default QuestionFromSection;
