import React, { createContext, useContext, useEffect, useState, useRef } from 'react';
import { fetchWithAuth } from '../fetchWithAuth';

const UserContext = createContext({
  user: null,
  loading: true,
  error: null,
  refreshUser: () => {},
});

export function UserProvider({ children }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const fetchedOnce = useRef(false);

  const fetchUser = async () => {
    if (fetchedOnce.current && loading) return;
    setLoading(true);
    setError(null);
    
    try {
      const token = localStorage.getItem('access');
      if (token) {
        const API_URL = import.meta.env.VITE_EFC_API_URL;
        const response = await fetchWithAuth(`${API_URL}/user/users/me/`);
        
        if (response.ok) {
          const userData = await response.json();
          setUser(userData);
        } else {
          setUser(null);
        }
      } else {
        setUser(null);
      }
    } catch (err) {
      console.error('Error fetching user:', err);
      setError(err);
      setUser(null);
    }
    
    setLoading(false);
    fetchedOnce.current = true;
  };

  useEffect(() => {
    fetchUser();
    const handler = () => {
      fetchedOnce.current = false;
      fetchUser();
    };
    window.addEventListener('authStateChanged', handler);
    return () => window.removeEventListener('authStateChanged', handler);
  }, []);

  return (
    <UserContext.Provider value={{ user, loading, error, refreshUser: fetchUser }}>
      {children}
    </UserContext.Provider>
  );
}

export function useUser() {
  return useContext(UserContext);
}
