import React, { createContext, ReactNode, useEffect, useState } from "react";
import { getToken, removeToken, storeToken } from "../utils/storage";

interface AuthContextType {
  token: string | null;
  isHydrated: boolean;
  login: (token: string) => Promise<void>;
  logout: () => Promise<void>;
}

export const AuthContext = createContext<AuthContextType>({
  token: null,
  isHydrated: false,
  login: async () => {},
  logout: async () => {},
});

export const AuthProvider = ({ children }: { children: ReactNode }) => {
  const [token, setToken] = useState<string | null>(null);
  const [isHydrated, setIsHydrated] = useState(false);

  useEffect(() => {
    const hydrate = async () => {
      const savedToken = await getToken();
      setToken(savedToken);
      setIsHydrated(true);
    };

    void hydrate();
  }, []);

  const login = async (nextToken: string) => {
    setToken(nextToken);
    await storeToken(nextToken);
  };

  const logout = async () => {
    setToken(null);
    await removeToken();
  };

  return (
    <AuthContext.Provider value={{ token, isHydrated, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};
