// src/hooks/useVerifyOtpForm.ts
"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";

import { verifyOtp } from "@/app/(pages)/(auth)/action";
import {
  defaultVerifyOtpValues,
  VerifyOtpFormData,
  verifyOtpSchema,
} from "@/src/entities/models/auth/verify-otp.model";
import { useNavigations } from "@/app/_hooks/use-navigations";
import { toast } from "sonner";

export function useVerifyOtpForm(initialEmail: string) {
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [message, setMessage] = useState<string | null>(null);
  const { router } = useNavigations();

  const form = useForm<VerifyOtpFormData>({
    resolver: zodResolver(verifyOtpSchema),
    defaultValues: { ...defaultVerifyOtpValues, email: initialEmail },
  });

  const onSubmit = async (data: VerifyOtpFormData) => {
    setIsSubmitting(true);
    setMessage(null);

    try {
      const result = await verifyOtp(data);

      if (result.success) {
        setMessage(result.message);
        // Redirect or update UI state as needed
        toast.success(result.message);
        if (result.redirectTo) {
          router.push(result.redirectTo);
        }
      } else {
        toast.error(result.message);
        form.setError("token", { type: "manual", message: result.message });
      }
    } catch (error) {
      console.error("OTP verification failed", error);
      toast.error("An unexpected error occurred. Please try again.");
      form.setError("token", {
        type: "manual",
        message: "An unexpected error occurred. Please try again.",
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return {
    form,
    isSubmitting,
    message,
    onSubmit,
  };
}
