import { createContext, useContext, useCallback, type ReactNode } from "react";
import { authClient, type AuthSession } from "./auth-client";

interface AuthContextValue {
  session: AuthSession | null;
  isPending: boolean;
  isAuthenticated: boolean;
  signIn: (password: string) => Promise<void>;
  signOut: () => Promise<void>;
  changePassword: (currentPassword: string, newPassword: string) => Promise<void>;
}

const AuthContext = createContext<AuthContextValue | null>(null);

export function AuthProvider({ children }: { children: ReactNode }) {
  const { data: session, isPending } = authClient.useSession();

  const signIn = useCallback(async (password: string) => {
    const { error } = await authClient.signIn.email({
      email: "jselesan@gmail.com",
      password,
    });
    if (error) throw error;
  }, []);

  const signOut = useCallback(async () => {
    await authClient.signOut();
  }, []);

  const changePassword = useCallback(
    async (currentPassword: string, newPassword: string) => {
      const { error } = await authClient.changePassword({
        currentPassword,
        newPassword,
      });
      if (error) throw error;
    },
    [],
  );

  return (
    <AuthContext.Provider
      value={{
        session: session ?? null,
        isPending,
        isAuthenticated: !!session,
        signIn,
        signOut,
        changePassword,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

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