import React, { createContext, useContext, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { userSessionService, LoginResponse } from './api';

interface AuthContextType {
  isAuthenticated: boolean;
  userData: LoginResponse | null;
  logout: () => void;
  checkAuthStatus: () => boolean;
  login: (userData: LoginResponse) => void;
}

const AuthContext = createContext<AuthContextType>({
  isAuthenticated: false,
  userData: null,
  logout: () => {},
  checkAuthStatus: () => false,
  login: () => {},
});

export const useAuth = () => useContext(AuthContext);

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(userSessionService.isAuthenticated());
  const [userData, setUserData] = useState<LoginResponse | null>(userSessionService.getSession());
  const navigate = useNavigate();

  // Check session on mount
  useEffect(() => {
    checkAuthStatus();
  }, []);

  const checkAuthStatus = (): boolean => {
    const isAuthValid = userSessionService.isAuthenticated();
    setIsAuthenticated(isAuthValid);
    setUserData(userSessionService.getSession());
    return isAuthValid;
  };

  const login = (userData: LoginResponse) => {
    userSessionService.setSession(userData);
    setIsAuthenticated(true);
    setUserData(userData);
    
    // Force a refresh of the page to ensure all components update
    const roleName = userData.roleName?.toLowerCase() || '';
    
    // Check if user is a client
    if (roleName === "client") {
      window.location.href = "/production-bugs";
    } 
    // Check if user has HR-related role (Admin, CEO, COO, or any role containing 'hr')
    else if (roleName === "admin" || roleName === "ceo" || roleName === "coo" || roleName.includes("hr")) {
      window.location.href = "/employees";
    } 
    // Default redirect to tasks for other roles
    else {
      window.location.href = "/tasks";
    }
  };

  const logout = () => {
    userSessionService.clearSession();
    setIsAuthenticated(false);
    setUserData(null);
    navigate('/login', { replace: true });
  };

  return (
    <AuthContext.Provider value={{ isAuthenticated, userData, logout, checkAuthStatus, login }}>
      {children}
    </AuthContext.Provider>
  );
};

// Auth guard component
export const RequireAuth: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { isAuthenticated } = useAuth();
  const navigate = useNavigate();

  useEffect(() => {
    if (!isAuthenticated) {
      navigate('/login', { replace: true });
    }
  }, [isAuthenticated, navigate]);

  return isAuthenticated ? <>{children}</> : null;
}; 