import React from 'react';
import { Navigate } from 'react-router-dom';
import useAuthStore from '../../../store/useAuthStore';

interface AccountantRouteProps {
  children: React.ReactNode;
}

const AccountantRoute: React.FC<AccountantRouteProps> = ({ 
  children
}) => {
  const { isAuthenticated, userInfo, isLoading } = useAuthStore();
  
  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 - redirect to login page
  if (!isAuthenticated) {
    return <Navigate to="/accountant/login" replace />;
  }

  // Check if user is accountant
  const isAccountant = userInfo?.role === 'accountant';
  if (!isAccountant) {
    // Redirect to appropriate dashboard based on role
    if (userInfo?.role === 'admin') {
      return <Navigate to="/admin/dashboard" replace />;
    } else if (userInfo?.role === 'staff') {
      return <Navigate to="/staff/dashboard" replace />;
    }
    return <Navigate to="/" replace />;
  }

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

export default AccountantRoute;

