export default function useLocalAuth() {
  const { cookieConfig } = useRuntimeConfig().public;

  const _address = {
    country: "",
    address1: "",
    address2: "",
    city: "",
    province: "",
    postalCode: "",
  };

  const user = {
    _id: "",
    givenName: "",
    middleName: "",
    surname: "",
    address: _address,
    email: "",
    password: "",
    type: "",
    createdAt: "",
    organization: "",
    role: "",
    primaryPhone: "",
    mobilePhone: "",
    serviceProviders: [],
  };

  const currentUser = useState(
    "currentUser",
    (): TUser | null => JSON.parse(JSON.stringify(user))
  );

  async function authenticate() {
    const user = useCookie("user", cookieConfig).value;

    const { data: getCurrentUserReq, error: getCurrentUserErr } =
      await useLazyAsyncData("getCurrentUser", () =>
        useNuxtApp().$api<TUser>(`/api/users/id/${user}`)
      );

    watchEffect(() => {
      currentUser.value = getCurrentUserReq.value as TUser | null;
    });

    watchEffect(() => {
      if (getCurrentUserErr.value) {
        // Redirect to login page if user authentication fails
        navigateTo({ name: "index" });
      }
    });
  }

  async function login({ email = "", password = "" }) {
    return useNuxtApp().$api<Record<string, any>>("/api/auth", {
      method: "POST",
      body: JSON.stringify({ email, password }),
    });
  }

  function setSession({ sid = "", user = "" }) {
    useCookie("sid", cookieConfig).value = sid;
    useCookie("user", cookieConfig).value = user;
  }

  function clearCookies() {
    useCookie("sid", cookieConfig).value = null;
    useCookie("user", cookieConfig).value = null;
    useCookie("organization", cookieConfig).value = null;
  }

  async function logout() {
    const sid = useCookie("sid", cookieConfig).value;
    if (sid) {
      try {
        await useNuxtApp().$api(`/api/auth/${sid}`, {
          method: "DELETE",
        });

        clearCookies();
      } catch (error) {
        console.error("Logout failed:", error);
      }
    }
  }

  async function getCurrentUser() {
    const user = useCookie("user", cookieConfig).value;
    if (!user) return null;
    const _user = await useNuxtApp().$api<TUser>(`/api/users/id/${user}`, {
      method: "GET",
    });
    currentUser.value = _user;
    return _user;
  }

  async function forgotPassword(email: string) {
    if (!email) {
      throw new Error("Email is required for password reset request.");
    }

    try {
      return await useNuxtApp().$api<Record<string, any>>(
        "/api/auth/forget-password",
        {
          method: "POST",
          body: JSON.stringify({ email }),
          headers: { "Content-Type": "application/json" },
        }
      );
    } catch (error) {
      console.error("Error in password reset request:", error);
      throw error;
    }
  }

  async function resetPassword(
    otp: string,
    newPassword: string,
    passwordConfirmation: string
  ) {
    try {
      return await useNuxtApp().$api<Record<string, any>>(
        "/api/auth/reset-password",
        {
          method: "POST",
          body: JSON.stringify({ otp, newPassword, passwordConfirmation }),
          headers: { "Content-Type": "application/json" },
        }
      );
    } catch (error) {
      console.error("Error resetting password:", error);
      throw error;
    }
  }

  function verify(id: string) {
    return useNuxtApp().$api<Record<string, any>>(`/api/auth/verify/${id}`, {
      method: "GET",
    });
  }

  function verifyInvite(inviteId: string) {
  if (!inviteId) throw new Error("inviteId is required");

  return useNuxtApp().$api<Record<string, any>>(
    `/api/auth/verify/invite/${inviteId}`,
    {
      method: "GET",
    }
  );
}

  async function updateVerificationStatus(id: string, status: string) {
    return useNuxtApp().$api<Record<string, any>>(`/api/auth/verification/status`, {
      method: "PATCH",
      body: { id, status },
    })
  }

  function signUp(email: string, referral: string) {
    return useNuxtApp().$api<Record<string, any>>("/api/auth/sign-up", {
      method: "POST",
      body: { email, referral },
    });
  }

  return {
    authenticate,
    login,
    setSession,
    logout,
    clearCookies,
    getCurrentUser,
    forgotPassword,
    resetPassword,
    currentUser,
    verify,
    verifyInvite,
    updateVerificationStatus,
    signUp,
  };
}
