import { useQuery } from "@tanstack/react-query";
import { useSession } from "@xtablo/shared/contexts/SessionContext";
import { Tables } from "@xtablo/shared/types/database.types";
import React, { useEffect } from "react";
import { createStore, StoreApi, useStore } from "zustand";
import { LoadingSpinner } from "../components/LoadingSpinner";
import { api } from "../lib/api";
import datadogRum from "../lib/rum";

export type User = Tables<"profiles"> & {
  streamToken: string | null;
};

const UserStoreContext = React.createContext<StoreApi<User> | null>(null);

export const UserStoreProvider = ({ children }: { children: React.ReactNode }) => {
  const { session } = useSession();
  const shouldFetchUser = !!session?.access_token;
  const { data: user, isPending } = useQuery<User | null>({
    queryKey: ["user"],
    queryFn: async () => {
      try {
        const { data: user } = await api.get<User>("/api/v1/users/me", {
          headers: {
            Authorization: `Bearer ${session?.access_token}`,
          },
        });
        return user;
      } catch (error) {
        console.error("Failed to get user:", error);
        return null;
      }
    },
    enabled: shouldFetchUser,
  });

  // Handle email verification
  // useEffect(() => {
  //   const checkEmailVerification = async () => {
  //     // Check if we're coming from an email verification link
  //     const hashParams = new URLSearchParams(window.location.hash.substring(1));
  //     const type = hashParams.get("type");

  //     if (type === "signup" || type === "email") {
  //       try {
  //         const {
  //           data: { user: supabaseUser },
  //         } = await supabase.auth.getUser();

  //         if (supabaseUser && supabaseUser.email_confirmed_at) {
  //           // Email was just verified
  //           const wasJustVerified = !sessionStorage.getItem("email_verified_shown");

  //           if (wasJustVerified) {
  //             // Clear the pending confirmation email
  //             localStorage.removeItem("pendingConfirmationEmail");

  //             // Mark that we've shown the verification success
  //             sessionStorage.setItem("email_verified_shown", "true");

  //             // Show success message
  //             toast.add({
  //               title: t("verifyEmail.successTitle"),
  //               description: t("verifyEmail.successDescription"),
  //               type: "success",
  //               position: "top-center",
  //             });

  //             // Clean up the URL hash
  //             window.history.replaceState(null, "", window.location.pathname);
  //           }
  //         }
  //       } catch (error) {
  //         console.error("Email verification check error:", error);
  //         toast.add({
  //           title: t("verifyEmail.errorTitle"),
  //           description: t("verifyEmail.error"),
  //           type: "error",
  //           position: "top-center",
  //         });
  //       }
  //     }
  //   };

  //   if (session) {
  //     checkEmailVerification();
  //   }
  // }, [session, t]);

  useEffect(() => {
    if (user) {
      datadogRum.setUser({
        id: user.id,
        email: user.email ?? undefined,
        name:
          user.first_name && user.last_name ? `${user.first_name} ${user.last_name}` : undefined,
        isReadOnly: user.is_temporary,
      });
    } else {
      datadogRum.clearUser();
    }
  }, [user]);

  if (isPending && shouldFetchUser) {
    return <LoadingSpinner />;
  }

  if (!user) {
    return children;
  }

  const store = createStore<User>()(() => user);

  return (
    <UserStoreContext.Provider value={store as StoreApi<User>}>
      {children}
    </UserStoreContext.Provider>
  );
};

export const useUser = () => {
  const store = React.useContext(UserStoreContext);
  if (!store) {
    throw new Error("Missing UserStoreProvider");
  }
  return useStore(store);
};

export const useMaybeUser = () => {
  const store = React.useContext(UserStoreContext);
  if (!store) {
    return null;
  }
  return useStore(store);
};

export const useIsReadOnlyUser = () => {
  const store = React.useContext(UserStoreContext);
  if (!store) {
    throw new Error("Missing UserStoreProvider");
  }
  return useStore(store).is_temporary;
};

// TestUserStoreProvider component
export const TestUserStoreProvider = ({
  children,
  user,
}: {
  children: React.ReactNode;
  user: User | null;
}) => {
  if (!user) {
    return children;
  }
  const store = createStore<User>()(() => user);

  return (
    <UserStoreContext.Provider value={store as StoreApi<User>}>
      {children}
    </UserStoreContext.Provider>
  );
};

// // Test useUser hook
// export const useTestUser = () => {
//   const store = React.useContext(TestUserStoreContext);
//   if (!store) {
//     throw new Error("Missing TestUserStoreProvider");
//   }
//   return useStore(store);
// };
