import { createContext, useContext, useState, useEffect, type ReactNode } from 'react';
import { AuthService, type UserSession } from '../services/auth.service';
import { ChatService } from '../services/chat.service';

interface AuthContextType {
  user: UserSession | null;
  loading: boolean;
  unreadCount: number;
  login: (user: UserSession) => void;
  logout: () => void;
  refreshSession: () => Promise<void>;
  fetchUnreadCount: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<UserSession | null>(null);
  const [loading, setLoading] = useState(true);
  const [unreadCount, setUnreadCount] = useState(0);

  const fetchUnreadCount = async () => {
    const currentUser = AuthService.getCurrentUser();
    if (currentUser) {
      try {
        const count = await ChatService.getUnreadCount(currentUser.id);
        setUnreadCount(count);
      } catch {
        setUnreadCount(0);
      }
    }
  };

  // Verificar sesión al cargar la app (Solo una vez)
  useEffect(() => {
    const initAuth = async () => {
      try {
        const sessionUser = await AuthService.checkSession();
        if (sessionUser) {
          setUser(sessionUser);
          await fetchUnreadCount(); // <--- 5. LLAMAR AL CARGAR LA APP
        } else {
          setUser(null);
          setUnreadCount(0);
        }
      } catch (error) {
        setUser(null);
        setUnreadCount(0);
      } finally {
        setLoading(false);
      }
    };

    initAuth();
  }, []);

  const login = (userData: UserSession) => {
    setUser(userData);
    localStorage.setItem('userProfile', JSON.stringify(userData));
    fetchUnreadCount();
  };

  const logout = () => {
    AuthService.logout();
    setUser(null);
    setUnreadCount(0);
    localStorage.removeItem('userProfile');
  };

  const refreshSession = async () => {
    const sessionUser = await AuthService.checkSession();
    setUser(sessionUser);
    if (sessionUser) {
      await fetchUnreadCount();
    }
  };

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

// Hook personalizado para usar el contexto fácilmente
export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}