"use client";

import { useRouter } from "next/navigation";
import { createContext, useContext, useEffect, useMemo, useState } from "react";
import { apiGet, User } from "@/lib/api";

type AuthContextValue = {
  token: string | null;
  setToken: (value: string | null) => void;
  logout: () => void;
  user: User | null;
  refreshUser: () => void;
};

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

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const [token, setTokenState] = useState<string | null>(null);
  const [user, setUser] = useState<User | null>(null);

  useEffect(() => {
    const stored = window.localStorage.getItem("atlas_token");
    setTokenState(stored);
    if (!stored) return;
    void apiGet<User>("/auth/me", stored).then(setUser).catch(() => setUser(null));
  }, []);

  useEffect(() => {
    if (!token) {
      setUser(null);
      return;
    }
    void apiGet<User>("/auth/me", token).then(setUser).catch(() => setUser(null));
  }, [token]);

  const value = useMemo<AuthContextValue>(() => {
    const setToken = (next: string | null) => {
      setTokenState(next);
      if (next) {
        window.localStorage.setItem("atlas_token", next);
      } else {
        window.localStorage.removeItem("atlas_token");
      }
    };
    return {
      token,
      setToken,
      logout: () => {
        setToken(null);
        router.push("/login");
      },
      user,
      refreshUser: () => {
        if (token) {
          void apiGet<User>("/auth/me", token).then(setUser).catch(() => setUser(null));
        }
      }
    };
  }, [router, token, user]);

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

export function useAuth() {
  const value = useContext(AuthContext);
  if (!value) {
    throw new Error("useAuth must be used inside AuthProvider");
  }
  return value;
}
