import { useState, useEffect, useCallback } from 'react';
import { getToken, setToken, removeToken, getUser, setUser, removeUser } from './auth';
import * as api from './api';

export function useAuth() {
  const [token, setTokenState] = useState<string | null>(null);
  const [user, setUserState] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      const t = await getToken();
      const u = await getUser();
      setTokenState(t);
      setUserState(u);
      setLoading(false);
    })();
  }, []);

  const loginFn = useCallback(async (email: string, password: string) => {
    const res = await api.login({ email, password });
    await setToken(res.data.token);
    await setUser(res.data.user);
    setTokenState(res.data.token);
    setUserState(res.data.user);
  }, []);

  const registerFn = useCallback(async (email: string, name: string, password: string) => {
    const res = await api.register({ email, name, password });
    await setToken(res.data.token);
    await setUser(res.data.user);
    setTokenState(res.data.token);
    setUserState(res.data.user);
  }, []);

  const logout = useCallback(async () => {
    await removeToken();
    await removeUser();
    setTokenState(null);
    setUserState(null);
  }, []);

  return { token, user, loading, login: loginFn, register: registerFn, logout };
}
