import { createContext, useContext, useState, useEffect } from 'react';
import api from '../services/api';

const AuthContext = createContext(null);

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchUser = async () => {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          setIsLoading(false);
          return;
        }

        const response = await api.get('/auth/user-info'); // Updated endpoint
        setUser(response.data);
      } catch (error) {
        console.error('Failed to fetch user info:', error);
        localStorage.removeItem('token');
      } finally {
        setIsLoading(false);
      }
    };

    fetchUser();
  }, []);
  // const login = async (username, password) => {
  //   try {
  //     const response = await api.post('/auth/login', { username, password });
  //     const { access_token, user } = response.data; // Make sure this matches your backend response
      
  //     localStorage.setItem('token', access_token);
  //     setUser(user);
  //     return user;
  //   } catch (error) {
  //     console.error('Login error:', error);
  //     throw error;
  //   }
  // };
  const login = async (username, password) => {
    try {
      const response = await api.post('/auth/login', { username, password });
      console.log('Login response:', response.data); // Debug log
      
      const { access_token } = response.data;
      localStorage.setItem('token', access_token);
      
      // Fetch user info after login
      const userResponse = await api.get('/auth/user-info');
      const userData = userResponse.data;
      
      setUser(userData);
      return userData; // Return the user data for redirect logic
    } catch (error) {
      console.error('Login error:', error);
      throw error;
    }
  };


 

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

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

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};