import { IInstrumentationService } from "@/src/application/services/instrumentation.service.interface";
import { IVerifyOtpUseCase } from "@/src/application/use-cases/auth/verify-otp.use-case";
import { z } from "zod";
import { InputParseError } from "@/src/entities/errors/common";

// export function useVerifyOtpForm(email: 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: email },
//   });

//   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,
//   };
// }

// export const useVerifyOtpController = (email: string) => {
//   const { verifyOtp } = useAuthActions()

//   const {
//     control,
//     register,
//     handleSubmit,
//     reset,
//     formState: { errors, isSubmitSuccessful },
//   } = useForm<VerifyOtpFormData>({
//     resolver: zodResolver(verifyOtpSchema),
//     defaultValues: { ...defaultVerifyOtpValues, email: email },
//   })

//   // Clear form after successful submission
//   useEffect(() => {
//     if (isSubmitSuccessful) {
//       reset({ ...defaultVerifyOtpValues, email })
//     }
//   }, [isSubmitSuccessful, reset, email])

//   const onSubmit = handleSubmit(async (data) => {
//     try {
//       await verifyOtp.mutate(data)
//     } catch (error) {
//       console.error("OTP verification failed", error)
//     }
//   })

//   // Function to handle auto-submission when all digits are entered
//   const handleOtpChange = (value: string, onChange: (value: string) => void) => {
//     onChange(value)

//     // Auto-submit when all 6 digits are entered
//     if (value.length === 6) {
//       setTimeout(() => {
//         onSubmit()
//       }, 300) // Small delay to allow the UI to update
//     }
//   }

//   return {
//     control,
//     register,
//     handleSubmit: onSubmit,
//     handleOtpChange,
//     errors,
//     isPending: verifyOtp.isPending,
//   }
// }

// Verify OTP Controller
const verifyOtpInputSchema = z.object({
  email: z.string().email("Please enter a valid email address"),
  token: z.string().min(6, "Please enter a valid OTP")
})

export type IVerifyOtpController = ReturnType<typeof verifyOtpController>

export const verifyOtpController =
  (
    instrumentationService: IInstrumentationService,
    verifyOtpUseCase: IVerifyOtpUseCase
  ) =>
    async (input: Partial<z.infer<typeof verifyOtpInputSchema>>) => {
      return await instrumentationService.startSpan({ name: "verifyOtp Controller" }, async () => {
        const { data, error: inputParseError } = verifyOtpInputSchema.safeParse(input)

        if (inputParseError) {
          throw new InputParseError("Invalid data", { cause: inputParseError })
        }

        return await verifyOtpUseCase({
          email: data.email,
          token: data.token
        })
      })
    }