// src/context/AuthContext.tsx
import { createContext, useState, useContext, type ReactNode, useEffect } from 'react';
import { loginUser } from '../services/apiService'; // Importaremos esta función
import type { LoginCredentials } from '../services/apiService'; // y este tipo
import { subscribeToLogout } from './authUtils';

interface AuthContextType {
  isAuthenticated: boolean;
  token: string | null;
  login: (credentials: LoginCredentials) => Promise<boolean>;
  logout: () => void;
}

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

export const AuthProvider = ({ children }: { children: ReactNode }) => {
  const [token, setToken] = useState<string | null>(null);

  useEffect(() => {
    // Al cargar la app, revisamos si ya hay un token guardado
    const storedToken = localStorage.getItem('admin-jwt-token');
    if (storedToken) {
      setToken(storedToken);
    }
  }, []);

  const logout = () => {
    localStorage.removeItem('admin-jwt-token');
    setToken(null);
  };

  useEffect(() => {
    // Nos suscribimos al evento de logout global.
    const handleLogout = () => logout();
    subscribeToLogout(handleLogout);
  }, []); // Se ejecuta solo una vez

  const login = async (credentials: LoginCredentials): Promise<boolean> => {
    try {
      const receivedToken = await loginUser(credentials);
      if (receivedToken) {
        localStorage.setItem('admin-jwt-token', receivedToken);
        setToken(receivedToken);
        return true;
      }
      return false;
    } catch (error) {
      console.error("Login failed:", error);
      // Asegurarse de que el usuario esté deslogueado si falla
      logout();
      return false;
    }
  };

  const value = {
    isAuthenticated: !!token,
    token,
    login,
    logout,
  };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

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