import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  EditTwoFA,
  getProfile,
  getTwoFactorStatus,
  login,
  logout,
  setTwoFA,
} from "@/record-management/services/api/authService";
import Cookies from "js-cookie";
// Update the path below to the correct relative path if needed
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { useNavigate } from "react-router-dom";
import { useAuth } from "@/shared/context/AuthContext";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { Spinner } from "@/shared/common/ui/sppiner";
import { createRoot } from "react-dom/client";
import { createElement } from "react";
import { User } from "lucide-react";
import { clearRememberMePreference } from "@/shared/utils/authPersistence";
import { disconnectSocket } from "@/record-management/components/common/socketInstance";
interface LoginPayload {
  email: string;
  password: string;
  tenantKey: string;
  unitId?: any;
}
export interface SetTwoFAPayload {
  isMFARequired: boolean;
}

export const useAuthUser = () => {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);
  const navigate = useNavigate();
  const {
    setUser,
    user: contextUser,
    selectedPositionId,
    setSelectedPositionId,
  } = useAuth();
  const {
    data: userDetails,
    isLoading,
    isError,
    refetch,
  } = useQuery<any>({
    queryKey: ["authUser"],
    queryFn: async () => {
      const { data } = await getProfile({
        tenantKey: Cookies.get("tenant-key")!,
        unitId: Cookies.get("unit-id") || "",
      });
      return data as any;
    },
    staleTime: 5 * 60 * 1000,
    retry: false,
  });

  const {
    mutate: loginMutate,
    isError: loginError,
    isSuccess: loginSuccess,
  } = useMutation({
    mutationFn: async ({
      email,
      password,
      tenantKey,
      unitId,
    }: LoginPayload) => {
      const response = await login({ email, password }, { tenantKey, unitId });

      return response.data;
    },
    onSuccess: (data, payload) => {
      Cookies.set("auth-token", data.token, { expires: 1 }); // expires in 1 day
      Cookies.set("tenant-key", payload.tenantKey, { expires: 1 });
      Cookies.set("unit-id", payload.unitId || "", { expires: 1 });

      toast.success(t("msg.loginSuccess"), {
        description: t("msg.redirecting"),
      });

      queryClient.invalidateQueries({ queryKey: ["authUser"] });

      navigate("/dashboard");
    },
    onError: (error) => {
      handleError(error);
    },
  });
  const {
    mutate: logoutMutate,
    isError: logoutError,
    isSuccess: logoutSuccess,
  } = useMutation({
    mutationFn: async () => {
      // Call the logout API endpoint
      await logout();
    },
    onSuccess: () => {
      disconnectSocket();

      // Clear user state
      setUser(null);
      setSelectedPositionId(null);

      // Clear all cookies
      Object.keys(Cookies.get()).forEach((cookieName) => {
        Cookies.remove(cookieName);
      });

      // Clear only auth-related localStorage keys. Tenant/theme config,
      // language, reminders, and other UI preferences should survive logout.
      clearRememberMePreference();
      localStorage.removeItem("token");

      // Invalidate specific queries instead of clearing all
      queryClient.invalidateQueries({ queryKey: ["authUser"] });

      // Show success message
      toast.success(t("msg.logoutSuccess") || "Logged out successfully");

      // Redirect to login page
      window.location.replace("/");
    },
    onError: (error) => {
      disconnectSocket();

      // Even if API call fails, still clear local data
      setUser(null);
      setSelectedPositionId(null);

      Object.keys(Cookies.get()).forEach((cookieName) => {
        Cookies.remove(cookieName);
      });

      clearRememberMePreference();
      localStorage.removeItem("token");
      queryClient.invalidateQueries({ queryKey: ["authUser"] });

      handleError(error);

      // Still redirect even if API fails
      window.location.replace("/");
    },
  });

  const { mutate: setTwoFactorAuth, isPending: isTwoFactorAuthLoading } =
    useMutation({
      mutationFn: async ({ isMFARequired }: SetTwoFAPayload) => {
        // This function sends the update to your backend
        await setTwoFA({ isMFARequired });
      },
      onSuccess: () => {
        toast.success("Two-Factor Authentication setting updated");
        queryClient.invalidateQueries({ queryKey: ["twoFAStatus"] });
      },
      onError: (error) => {
        handleError(error);
      },
    });

  const { data: twoFactorDatas, isLoading: isLoadingStatus } = useQuery({
    queryKey: ["twoFAStatus", userDetails], // query key MUST be an array or string[]
    queryFn: getTwoFactorStatus,
    enabled: !!userDetails,
  });
  const { mutate: editTwoFA } = useMutation({
    mutationFn: async ({
      id,
      isEnabled,
    }: {
      id: string;
      isEnabled: boolean;
    }) => {
      await EditTwoFA({ isMFARequired: isEnabled }, id); // your PUT request
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["twoFAStatus"] });
    },
  });
  const selectedPositionPermissionKeys =
    userDetails?.selectedPositionPermissionKeys || [];
  return {
    userDetails,
    selectedPositionPermissionKeys,
    isLoading,
    isError,
    refetch,
    login: loginMutate,
    logout: logoutMutate,
    loginSuccess,
    loginError,
    logoutSuccess,
    logoutError,
    setTwoFactorAuth: setTwoFactorAuth,
    twoFactorData: twoFactorDatas?.data?.items,
    isLoadingStatus,
    editTwoFA,
  };
};
