"use client";

import { useEffect, useState } from "react";
import firebaseApp, { isFirebaseConfigured } from "@/lib/firebase";
import { deleteCookie, hasCookie } from "cookies-next";
import useUserStore from "@/global-store/user";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import useSearchHistoryStore from "@/global-store/search-history";
import useLikeStore from "@/global-store/like";
import useCartStore from "@/global-store/cart";
import useCompareStore from "@/global-store/compare";
import { useFcmToken } from "@/hook/use-fcm-token";
import { authService } from "@/services/auth";
import { useRouter } from "next/navigation";

export const useAuth = () => {
  const router = useRouter();
  const queryClient = useQueryClient();
  const [isSignedIn, setIsSignedIn] = useState(false);
  const { signOut: localSignOut } = useUserStore();
  const clearSearchHistory = useSearchHistoryStore((state) => state.clear);
  const clearLikeList = useLikeStore((state) => state.clear);
  const clearCart = useCartStore((state) => state.clear);
  const clearCompareList = useCompareStore((state) => state.clear);
  const { fcmToken } = useFcmToken();
  const { mutate: serverLogout } = useMutation({
    mutationFn: (body: { token: string }) => authService.logout(body),
    mutationKey: ["logout"],
  });
  const handleLogoutLocal = async () => {
    if (isFirebaseConfigured && firebaseApp) {
      const { signOut, getAuth } = await import("firebase/auth");
      const auth = getAuth(firebaseApp);
      await signOut(auth);
    }
    setIsSignedIn(false);
    deleteCookie("token");
    localSignOut();
    queryClient.clear();
    clearSearchHistory();
    clearLikeList("shop");
    clearLikeList("master");
    clearCart();
    clearCompareList();
  };
  const logOut = async () => {
    router.replace("/");
    if (fcmToken) {
      serverLogout(
        { token: fcmToken },
        {
          onSuccess: async () => {
            router.replace("/");
            await handleLogoutLocal();
          },
        }
      );
      return;
    }
    await handleLogoutLocal();
  };

  const googleSignIn = async () => {
    if (!isFirebaseConfigured || !firebaseApp) {
      throw new Error("Firebase is not configured");
    }
    const { signInWithPopup, GoogleAuthProvider, getAuth } = await import("firebase/auth");
    const auth = getAuth(firebaseApp);
    const googleAuthProvider = new GoogleAuthProvider();
    return signInWithPopup(auth, googleAuthProvider);
  };

  const appleSignIn = async () => {
    if (!isFirebaseConfigured || !firebaseApp) {
      throw new Error("Firebase is not configured");
    }
    const { signInWithPopup, OAuthProvider, getAuth } = await import("firebase/auth");
    const auth = getAuth(firebaseApp);
    const appleAuthProvider = new OAuthProvider("apple.com");
    appleAuthProvider.addScope("email");
    appleAuthProvider.addScope("name");
    return signInWithPopup(auth, appleAuthProvider);
  };

  const facebookSignIn = async () => {
    if (!isFirebaseConfigured || !firebaseApp) {
      throw new Error("Firebase is not configured");
    }
    const { FacebookAuthProvider, signInWithPopup, getAuth } = await import("firebase/auth");
    const auth = getAuth(firebaseApp);
    const facebookAuthProvider = new FacebookAuthProvider();
    return signInWithPopup(auth, facebookAuthProvider);
  };

  const phoneNumberSignIn = async (
    phoneNumber: string,
    options?: { mode?: "register" | "forgot" }
  ) => {
    const phone = phoneNumber.replace(/\D/g, "");
    const mode = options?.mode || "register";

    // Always prefer backend SMS when Firebase is not fully configured
    if (!isFirebaseConfigured || !firebaseApp) {
      const response =
        mode === "forgot"
          ? await authService.sendForgotPasswordSms({ phone })
          : await authService.register({ phone });
      const payload = response?.data ?? response;
      const verifyId = String((payload as any)?.verifyId || "");
      if (!verifyId) {
        throw new Error("verifyId missing from SMS response");
      }
      if (typeof window !== "undefined") {
        sessionStorage.setItem("sms_verify_id", verifyId);
        sessionStorage.setItem("sms_verify_phone", phone);
      }
      return {
        verifyId,
        phone: (payload as any)?.phone || phone,
        confirm: async (otp: string) => ({
          user: {
            getIdToken: async () => otp,
          },
          verifyId,
          verifyCode: otp,
          phone,
        }),
      };
    }

    const { getAuth, signInWithPhoneNumber, RecaptchaVerifier } = await import("firebase/auth");
    const auth = getAuth(firebaseApp);
    const appVerifier = new RecaptchaVerifier(auth, "sign-in-button", {
      size: "invisible",
      callback: () => {
        console.log("Callback!");
      },
    });
    return signInWithPhoneNumber(auth, phoneNumber, appVerifier);
  };

  useEffect(() => {
    setIsSignedIn(hasCookie("token"));
  }, []);

  return { logOut, googleSignIn, appleSignIn, facebookSignIn, phoneNumberSignIn, isSignedIn };
};
