import React, { useEffect } from 'react';
import { Navigate } from 'react-router-dom';
import useAuthStore from '../../store/useAuthStore';
import { useAuthModal } from '../../contexts/AuthModalContext';

interface AccountantRouteProps {
  children: React.ReactNode;
}

const AccountantRoute: React.FC<AccountantRouteProps> = ({ 
  children
}) => {
  const { isAuthenticated, userInfo, isLoading } = useAuthStore();
  const { openModal } = useAuthModal();
  
  // Open login modal if not authenticated
  useEffect(() => {
    if (!isLoading && !isAuthenticated) {
      openModal('login');
    }
  }, [isLoading, isAuthenticated, openModal]);
  
  if (isLoading) {
    return (
      <div 
        className="min-h-screen flex items-center 
          justify-center bg-gray-50"
      >
        <div className="text-center">
          <div 
            className="animate-spin rounded-full h-12 w-12 
              border-b-2 border-indigo-600 mx-auto"
          />
          <p className="mt-4 text-gray-600">
            Authenticating...
          </p>
        </div>
      </div>
    );
  }

  // Don't render children if not authenticated (modal will be shown)
  if (!isAuthenticated) {
    return null; // Modal will be shown by AuthModalManager
  }

  // Check if user is accountant
  const isAccountant = userInfo?.role === 'accountant';
  if (!isAccountant) {
    return <Navigate to="/" replace />;
  }

  return <>{children}</>;
};

export default AccountantRoute;

