import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from "react";
import { apiFetch, setToken, clearToken, getToken } from "./api";

type User = {
  id: string;
  username: string;
  phone: string;
};

type AuthContextType = {
  user: User | null;
  isLoading: boolean;
  register: (username: string, phone: string) => Promise<void>;
  login: (phone: string) => Promise<void>;
  logout: () => void;
};

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

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(!!getToken());

  useEffect(() => {
    if (!getToken()) return;
    apiFetch<User>("/auth/me")
      .then(setUser)
      .catch(() => clearToken())
      .finally(() => setIsLoading(false));
  }, []);

  const register = useCallback(async (username: string, phone: string) => {
    const data = await apiFetch<{ user: User; token: string }>("/auth/register", {
      method: "POST",
      body: JSON.stringify({ username, phone }),
    });
    setToken(data.token);
    setUser(data.user);
  }, []);

  const login = useCallback(async (phone: string) => {
    const data = await apiFetch<{ user: User; token: string }>("/auth/login", {
      method: "POST",
      body: JSON.stringify({ phone }),
    });
    setToken(data.token);
    setUser(data.user);
  }, []);

  const logout = useCallback(() => {
    clearToken();
    setUser(null);
  }, []);

  return (
    <AuthContext.Provider value={{ user, isLoading, register, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
}

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