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

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 <div>Loading...</div>;
  }

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