import {
  createContext,
  PropsWithChildren,
  useCallback,
  useContext,
  useMemo,
} from "react";
import { MantineColor, MantineColorScheme } from "@mantine/core";
import { useQueryClient } from "@tanstack/react-query";
import { Player } from "@/features/players/types";
import { playerKeys, playerQueries, useMe } from "@/features/players/queries";

interface AuthData {
  user: Player | undefined;
  metadata: {
    accentColor: MantineColor;
    colorScheme: MantineColorScheme;
    locale?: string;
  };
  roles: string[];
  phone: string;
}

export const defaultAuthData: AuthData = {
  user: undefined,
  metadata: { accentColor: "blue", colorScheme: "dark" },
  roles: [],
  phone: ""
};

export interface AuthContextType extends AuthData {
  set: ({ user, metadata, roles }: Partial<AuthContextType>) => void;
}

const AuthContext = createContext<AuthContextType>({
  ...defaultAuthData,
  set: () => {},
});

export const AuthProvider: React.FC<PropsWithChildren> = ({ children }) => {
  const queryClient = useQueryClient();
  const { data } = useMe();

  const set = useCallback(
    (updates: Partial<AuthData>) => {
      queryClient.setQueryData(
        playerKeys.auth,
        (oldData: AuthData | undefined) => {
          const currentData = oldData || defaultAuthData;
          return {
            ...currentData,
            ...updates,
            metadata: updates.metadata
              ? { ...currentData.metadata, ...updates.metadata }
              : currentData.metadata,
          };
        }
      );
    },
    [queryClient]
  );

  const value = useMemo(
    () => ({
      user: data?.user,
      metadata: data?.metadata || { accentColor: "blue" as MantineColor, colorScheme: "dark" as MantineColorScheme },
      roles: data?.roles || [],
      phone: data?.phone || "",
      set,
    }),
    [data, set]
  );

  return <AuthContext value={value}>{children}</AuthContext>;
};

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
};
