// src/contexts/AuthContext.tsx
import React, { createContext, useContext, useEffect, useState, useCallback } from 'react';
import { authService, UserProfile } from '../api/services/authService';
import { tokenManager } from '../api/auth/tokenManager';

interface AuthContextType {
  user: UserProfile | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  login: (email: string, password: string) => Promise<void>;
  register: (data: any) => Promise<void>;
  logout: () => Promise<void>;
  updateProfile: (updates: Partial<UserProfile>) => Promise<void>;
  refreshUser: () => Promise<void>;
}

// THIS LINE IS CRUCIAL AND MUST BE PRESENT AND UNCOMMENTED
const AuthContext = createContext<AuthContextType | null>(null);

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

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [user, setUser] = useState<UserProfile | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // Initialize auth state
  useEffect(() => {
    const initAuth = async () => {
      try {
        await tokenManager.initialize();

        if (authService.isAuthenticated()) {
          const profile = await authService.getCurrentUser();
          setUser(profile);
        }
      } catch (error) {
        console.error('Auth initialization failed:', error);
      } finally {
        setIsLoading(false);
      }
    };

    initAuth();
  }, []);

  const login = useCallback(async (email: string, password: string) => {
    const profile = await authService.login({ email, password });
    setUser(profile);
  }, []);

  const register = useCallback(async (data: any) => {
    const profile = await authService.register(data);
    setUser(profile);
    await login(data.email, data.password); // Reuse the login function
  }, [login]);

  const logout = useCallback(async () => {
    await authService.logout();
    setUser(null);
  }, []);

  const updateProfile = useCallback(async (updates: Partial<UserProfile>) => {
    const updated = await authService.updateProfile(updates);
    setUser(updated);
  }, []);

  const refreshUser = useCallback(async () => {
    if (authService.isAuthenticated()) {
      const profile = await authService.getCurrentUser();
      setUser(profile);
    }
  }, []);

  // Set up token refresh interval
  useEffect(() => {
    if (!user) return;

    const interval = setInterval(async () => {
      try {
        await tokenManager.getAccessToken();
      } catch (error) {
        console.error('Token refresh failed:', error);
        await logout();
      }
    }, 60000); // 1 minute

    return () => clearInterval(interval);
  }, [user, logout]);

  return (
    <AuthContext.Provider // This is now defined!
      value={{
        user,
        isAuthenticated: !!user,
        isLoading,
        login,
        register,
        logout,
        updateProfile,
        refreshUser
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};