import { useState } from "react";
import { useForm } from "react-hook-form";
import { ApiRequestStatus } from "../../common/const/api_request_states";
import { useDataContext } from "../../common/contexts/data_context";
import { router } from "expo-router";
import { useAuth } from "../contexts/auth_context";

interface VerifyAccountFormValues {
  code: string;
}

export const useVerifyAccount = () => {
  const { authRepository } = useDataContext();
  const { verify } = useAuth();
  const { setValue, handleSubmit } = useForm<VerifyAccountFormValues>({
    defaultValues: {
      code: "",
    },
  });
  const [requestStatus, setRequestStatus] = useState<ApiRequestStatus>(
    ApiRequestStatus.IDLE
  );

  const setLoading = () => setRequestStatus(ApiRequestStatus.LOADING);

  const onValidSubmit = async (values: VerifyAccountFormValues) => {
    setLoading();
    try {
      await authRepository!.verifyAccount(values.code);
      await verify();
      router.replace("/(tabs)");
    } catch (error) {
      setRequestStatus(ApiRequestStatus.ERROR);
    }
  };

  const getNewResetCode = async () => {
    setLoading();
    try {
      await authRepository!.resendConfirmationCode();
    } catch (error) {
    } finally {
      setRequestStatus(ApiRequestStatus.SUCCESS);
    }
  };

  const onSubmit = async () => {
    await handleSubmit(onValidSubmit, (err) => {
      console.log(err);
    })();
  };

  return { setValue, requestStatus, onSubmit, getNewResetCode };
};
