import { useCreateAdmin, useUpdateAdmin } from "@/hooks/queries";
import { ICreateAdminCredentials } from "@/lib/api";
import { useIsMutating } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { SubmitHandler, useForm } from "react-hook-form";

interface IProps {
  editMode?: boolean;
  defaultValues?: ICreateAdminCredentials;
  id?: string;
}
const useCreateAdminPresenter = ({
  editMode = false,
  defaultValues,
  id,
}: IProps) => {
  const isMutating = useIsMutating();
  const {
    register,
    formState: { errors },
    handleSubmit,
    watch,
  } = useForm<ICreateAdminCredentials>({
    mode: "onChange",
    defaultValues,
  });

  const { mutate: createAdmin } = useCreateAdmin();
  const { mutate: updateAdmin } = useUpdateAdmin(id as string);
  const onSubmit: SubmitHandler<ICreateAdminCredentials> = (data) => {
    if (editMode) {
      updateAdmin({ id: id as string, credentials: data });
    } else {
      createAdmin({ ...data, role: "admin" });
    }
  };
  const router = useRouter();
  return {
    errors,
    register,
    handleSubmit,
    router,
    isMutating,
    onSubmit,
    watchForm: watch,
  };
};

export default useCreateAdminPresenter;
