import { useEffect, useState } from "react";
import { ResetPasswordForm } from "../components/reset_password_form";
import { CodeForm } from "../components/code_form";
import { PasswordForm } from "../components/password_form";
import { useResetPassword } from "./useResetPassword";

interface ResetPasswordSlide {
  slide: JSX.Element;
  callback: () => Promise<void>;
  onError?: () => void;
}

export const useResetPasswordControl = () => {
  const {
    control,
    getResetCode,
    setValue,
    onSubmit,
    status: requestStatus,
  } = useResetPassword();
  const slides: ResetPasswordSlide[] = [
    {
      slide: <ResetPasswordForm control={control} />,
      callback: async () => {
        await getResetCode();
      },
    },
    {
      slide: <CodeForm setValue={setValue} />,
      callback: async () => {
        console.log("Reset Password 1");
      },
    },
    {
      slide: <PasswordForm control={control} />,
      callback: async () => {
        onSubmit();
      },
    },
  ];
  const [step, setStep] = useState(0);
  const [slide, setSlide] = useState(slides[step]);
  const [isLast, setIsLast] = useState(step === slides.length - 1);
  const [isFirst, setIsFirst] = useState(step === 0);

  const onNext = async () => {
    try {
      await slide.callback();
      setStep(step + 1);
    } catch (error) {
      slide.onError && slide.onError();
    }
  };

  const onPrevious = () => {
    setStep(step - 1);
  };

  const onFinish = () => {
    try {
      slide.callback();
    } catch (e) {
      slide.onError && slide.onError();
    }
  };

  useEffect(() => {
    setSlide(slides[step]);
    setIsFirst(step === 0);
    setIsLast(step === slides.length - 1);
  }, [step]);

  return {
    onNext,
    onFinish,
    slide: slide.slide,
    isFirst,
    isLast,
    onPrevious,
    requestStatus,
  };
};
