/** @format */


import { useAuthStore } from "@/providers/AuthStoreProviders";
import { getAuthService } from "@/services/auth";
import { AuthStore } from "@/stores/auth";
import { showToast } from "@/utils/toast";
import { router } from "expo-router";
import { useCallback, useEffect, useRef, useState } from "react";
import { useAuthHandler } from "./useAuthHandler";
import { useQueryMutation } from "./mutate/useQueryMutation";

export default function useSocialAuth() {
  const [loading, setLoading] = useState(false);
  const [loadingProvider, setLoadingProvider] = useState<string | null>(null);
  const { redirect, setOtpBreakTimer } = useAuthHandler();
  const { login } = useAuthStore((state: AuthStore) => state);
  const isMountedRef = useRef(true);
  const { mutate, isLoading: isSocialAuthLoading } = useQueryMutation({
    isPublic: true,
    url: "/login/google/callback/mobile",
  });

  useEffect(() => {
    return () => {
      isMountedRef.current = false;
    };
  }, []);

  const stopLoading = useCallback(() => {
    if (!isMountedRef.current) return;
    setLoading(false);
    setLoadingProvider(null);
  }, []);

  const completeSocialLogin = useCallback(
    async (data: any) => {
      if (!data?.token || !data?.user) {
        throw new Error("Missing user or token in social auth response");
      }

      // Login first before any navigation decisions
      login(data.token, data.user);

      if (data?.user?.is_2fa_enabled) {
        setOtpBreakTimer(data?.user?.email);
        router.replace(
          `/(auth)/verify-2fa?email=${encodeURIComponent(data.user.email)}` as any,
        );
        return;
      }

      const redirectURL = await redirect(data?.user);

      // Use "/" for tabs destination to avoid Android "addViewAt: failed to insert view" crash.
      // root index.tsx reads the saved token and uses <Redirect href="/(tabs)"> which
      // resolves after the render cycle — safe from the concurrent-render crash.
      const finalURL = !redirectURL || redirectURL === "/(tabs)"
        ? "/"
        : (redirectURL as any);

      router.replace(finalURL);
    },
    [login, redirect, setOtpBreakTimer],
  );

  const handleSocialLogin = useCallback(
    async (providerName: string) => {
      try {
        setLoading(true);
        setLoadingProvider(providerName);

        const service = getAuthService(providerName);
        const result = await service.signIn();

        if (result.type === "cancelled") {
          return;
        }
        mutate(
          {
            access_token: result?.accessToken,
            updatedUrl: `/login/${providerName}/callback/mobile`,
          },
          {
            onSuccess: async (response: any) => {
              const data = response?.data;
              completeSocialLogin(data);
            },
            onError: (err) => {
              setLoading(false);
              console.log(err, "Error");
            },
          },
        );
      } catch (err: any) {
        console.log("Social auth error", providerName, err);
        showToast({
          text: err?.message || "Social sign in failed. Please try again.",
          type: "error",
        });
      } finally {
        stopLoading();
      }
    },
    [completeSocialLogin, stopLoading, mutate],
  );

  return {
    handleSocialLogin,
    isSocialAuthLoading: loading || isSocialAuthLoading,
    loadingProvider,
  };
}
