import { useState } from "react";
import { apiSetPassword } from "../../services/AuthService";
import { customizeToast, getBackendErrorMessage } from "../../utils";

interface SetPasswordData {
  token: string;
  password: string;
}

function useSetPasswordService() {
  const [loading, setLoading] = useState(false);

  // Set Password
  const setPasswordAsync = async (data: SetPasswordData) => {
    try {
      setLoading(true);
      const response = await apiSetPassword(data);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        customizeToast("Password set successfully", "success");
        return {
          success: true,
          data: response.data,
          message: response.data?.message || "Password set successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage = response.data?.message || "Failed to set password";
        customizeToast(errorMessage, "danger");
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      setLoading(false);
      // Handle network errors or other exceptions
      const errorMessage =
        getBackendErrorMessage(error, "Failed to set password") ||
        error?.response?.data?.message ||
        error.toString();
      customizeToast(errorMessage, "danger");
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    } finally {
      setLoading(false);
    }
  };

  return {
    loading,
    setPassword: setPasswordAsync,
  };
}

export default useSetPasswordService;
