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

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,
  });

  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);
};

// TestUserStoreProvider component
export const TestUserStoreProvider = ({
  children,
  user,
}: {
  children: React.ReactNode;
  user: User;
}) => {
  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);
// };
