import { FC, memo, useEffect, useState } from "react";
import { validEmail } from "../utils";
import ContinueButton from "./ContinueButton";
import EmailInput from "./EmailInput";

interface PropsType {
  connected?: boolean;
  emailRequired?: boolean;
  handleEmailNextClick?: (email: string) => void;
  handleContinueClick: (email: string) => void;
  onFocus: (isFocus: boolean) => void;
  btnStyle?: {
    textColor?: string;
    bgColor?: string;
  };
}
const Form: FC<PropsType> = ({
  connected,
  emailRequired = true,
  handleContinueClick,
  handleEmailNextClick,
  onFocus,
  btnStyle,
}) => {
  const [email, setEmail] = useState("");
  const [isFocus, setIsFocus] = useState(false);
  const [emailError, setEmailError] = useState("");
  const handleClick = () => {
    if (emailRequired && !validEmail(email)) {
      setEmailError("Please enter a valid email address");
    } else {
      setEmailError("");
      handleEmailNextClick
        ? handleEmailNextClick(email)
        : handleContinueClick(email);
    }
  };

  useEffect(() => {
    onFocus(isFocus);
  }, [isFocus, onFocus]);

  useEffect(() => {
    if (connected) {
      setEmail("");
    }
  }, [connected]);

  return (
    <>
      <EmailInput
        email={email}
        setEmailError={setEmailError}
        setEmail={setEmail}
        emailError={emailError}
        isFocus={isFocus}
        setIsFocus={setIsFocus}
      />

      <ContinueButton
        email={email}
        handleClick={handleClick}
        btnStyle={btnStyle}
      />
    </>
  );
};

export default memo(Form);
