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

const AuthContext = createContext();
const API_URL = import.meta.env.VITE_API_URL;

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [loading, setLoading] = useState(true);
  const [isRegistratonEnabled, setIsRetratonEnabled] = useState(null);

  // Automatically include credentials (cookies) in requests
  axios.defaults.withCredentials = true;

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const res = await axios.get(`${API_URL}/check`);
        setUser(res.data.user);
        setIsRetratonEnabled(res.data.allowRegistration);
      } catch (error) {
        if (typeof error.response.data.allowRegistration != "undefined") {
          setIsRetratonEnabled(error.response.data.allowRegistration);
        }else {
          setIsRetratonEnabled(false);
        }
          setIsAuthenticated(false);
          setUser(null);
      } finally {
        setLoading(false);
      }
    };

    checkAuth();
  }, []);

  const login = async (username, password) => {
    try {
      await axios.post(`${API_URL}/login`, {
        username,
        password,
      });

      const res = await axios.get(`${API_URL}/check`);
      setUser(res.data.user);
      setIsAuthenticated(true);
    } catch (error) {
      throw new Error('Login failed');
    }
  };

  const logout = async () => {
    try {
      await axios.post(`${API_URL}/logout`);
    } catch (error) {
      console.log("error") 
    }
    setUser(null);
    setIsAuthenticated(false);
  };

  const register = async (name, username, password) => {
    try {
      await axios.post(`${API_URL}/register`, {
        name,
        username,
        password,
      });
    } catch (error) {
      throw new Error('Registration failed');
    }
  };

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


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