import { useCallback } from 'react';

export function useAuth() {
  const login = useCallback((
    token: string,
    user: any,
    profile: any
  ) => {
    localStorage.setItem('authToken', token);
    localStorage.setItem('user', JSON.stringify(user));
    localStorage.setItem('profile', JSON.stringify(profile));
    console.log('login called', { token, user, profile });
  }, []);

  const logout = useCallback(() => {
    localStorage.removeItem('authToken');
    localStorage.removeItem('user');
    localStorage.removeItem('profile');
    console.log('logout called');
  }, []);

  const getToken = useCallback(() => {
    const token = localStorage.getItem('authToken');
    console.log('getToken called', token);
    return token;
  }, []);

  const getUser = useCallback(() => {
    try {
      const user = localStorage.getItem('user');
      const parsed = user ? JSON.parse(user) : null;
      console.log('getUser called', parsed);
      return parsed;
    } catch (e) {
      console.log('getUser error', e);
      return null;
    }
  }, []);

  const getProfile = useCallback(() => {
    try {
      const profile = localStorage.getItem('profile');
      const parsed = profile ? JSON.parse(profile) : null;
      console.log('getProfile called', parsed);
      return parsed && parsed.id ? parsed : null;
    } catch (e) {
      console.log('getProfile error', e);
      return null;
    }
  }, []);

  const isAuthenticated = useCallback(() => {
    const auth = !!getToken();
    console.log('isAuthenticated called', auth);
    return auth;
  }, [getToken]);

  const getAllData = useCallback(() => {
    const data = {
      token: getToken(),
      user: getUser(),
      profile: getProfile()
    };
    console.log('getAllData called', data);
    return data;
  }, [getToken, getUser, getProfile]);

  return {
    login,
    logout,
    getToken,
    getUser,
    getProfile,
    getAllData,
    isAuthenticated
  };
}
