import React, { useState, useEffect, FormEvent } from "react";
import { LogoIconLarge } from "../components/icons/Logo";
import EmailInput from "../components/forgotPassword/EmailInput";
import OTPVerification from "../components/forgotPassword/OTP_Verification";
import PasswordSetup from "../components/forgotPassword/PasswordSetup";
import ConfirmationMessage from "../components/forgotPassword/ConfirmationMessgae";
import { changePasswordApi } from "../services/factoryBuilder/signInSignUp/changePasswordApi";
import { checkEmailApi } from "../services/factoryBuilder/signInSignUp/checkEmailApi";
import { verifyOtpApi } from "../services/factoryBuilder/signInSignUp/verifyOtpApi";

const ForgotPassword: React.FC = () => {
  const [step, setStep] = useState(1);
  const [email, setEmail] = useState("");
  const [code, setCode] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [timer, setTimer] = useState(30);
  const [resetToken, setResetToken] = useState("");

  useEffect(() => {
    let countdown: NodeJS.Timeout;
    if (step === 2 && timer > 0) {
      countdown = setTimeout(() => setTimer((prev) => prev - 1), 1000);
    }
    return () => clearTimeout(countdown);
  }, [step, timer]);

  const resendCode = async () => {
    // TODO: call API to resend code
    setTimer(30);
    try {
      const emailResponse = await checkEmailApi(email);

      if (emailResponse.message == "OTP sent Successfully") {
        setCode(emailResponse.OTP);
      }
    } catch {}
  };
  const handleEmailSubmit = async (e: FormEvent<HTMLFormElement>) => {
    setTimer(30);
    try {
      const emailResponse = await checkEmailApi(email);

      if (emailResponse.message == "OTP sent Successfully") {
        setStep(2);
        setCode(emailResponse.OTP);
      }
    } catch {}
  };

  const handleOTPSubmit = async (e: FormEvent<HTMLFormElement>) => {
    try {
      const otpResponse = await verifyOtpApi(email, Number(code));

      if (otpResponse.message == "OTP verified successfully") {
        setResetToken(otpResponse.resetToken);
        setStep(3);
      } else {
        alert(otpResponse.message);
      }
    } catch {}
  };

  const handlePasswordSubmit = async (e: FormEvent<HTMLFormElement>) => {
    try {
      const passwordResponse = await changePasswordApi(
        resetToken,
        newPassword,
        confirmPassword
      );
      if (passwordResponse.message === "Password reset successfull!!") {
        setStep(4);
      }
    } catch {}
  };

  return (
    <div className="forgot-password-page auth-container">
      <div className="forgot-password-wrapper">
        <div className="logo-icon">
          <LogoIconLarge />
        </div>

        {step === 1 && (
          <>
            <EmailInput
              email={email}
              setEmail={setEmail}
              onSubmit={handleEmailSubmit}
            />
            <a href="/" className="login continue-button">
              Login
            </a>
          </>
        )}

        {step === 2 && (
          <>
            <OTPVerification
              code={code}
              email={email}
              timer={timer}
              setCode={setCode}
              onSubmit={handleOTPSubmit}
              resendCode={resendCode}
            />
            <a href="/" className="login">
              Login
            </a>
          </>
        )}

        {step === 3 && (
          <>
            <PasswordSetup
              newPassword={newPassword}
              confirmPassword={confirmPassword}
              setNewPassword={setNewPassword}
              setConfirmPassword={setConfirmPassword}
              onSubmit={handlePasswordSubmit}
            />
            <a href="/" className="login">
              Login
            </a>
          </>
        )}

        {step === 4 && <ConfirmationMessage />}
      </div>
    </div>
  );
};

export default ForgotPassword;
