import React, {
  createContext,
  useContext,
  useState,
  useEffect
} from 'react';

import api from '../services/api';

const AuthContext = createContext(null);

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const token = localStorage.getItem('token');
    const savedUser = localStorage.getItem('user');

    if (
      token &&
      savedUser &&
      savedUser !== "undefined"
    ) {
      try {
        setUser(JSON.parse(savedUser));

        api
          .get('/auth/me')
          .then((res) => {
            setUser(res.data);
            localStorage.setItem(
              'user',
              JSON.stringify(res.data)
            );
          })
          .catch(() => logout())
          .finally(() => setLoading(false));

      } catch (error) {
        console.error('Invalid localStorage data');

        localStorage.removeItem('token');
        localStorage.removeItem('user');

        setLoading(false);
      }

    } else {
      setLoading(false);
    }
  }, []);

  const login = async (email, password) => {
    const res = await api.post('/auth/login', {
      email,
      password
    });

    localStorage.setItem('token', res.data.token);

    localStorage.setItem(
      'user',
      JSON.stringify(res.data.user)
    );

    setUser(res.data.user);

    return res.data;
  };

  const register = async (data) => {
    const res = await api.post('/auth/register', data);
    return res.data;
  };

  const logout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    setUser(null);
  };

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

export const useAuth = () => useContext(AuthContext);