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

interface CustomerRouteProps {
  children: React.ReactNode;
}

const CustomerRoute: React.FC<CustomerRouteProps> = ({ 
  children
}) => {
  const { isAuthenticated, userInfo, isLoading } = useAuthStore();
  const { openModal } = useAuthModal();
  
  
  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">
            Loading...
          </p>
        </div>
      </div>
    );
  }

  
  if (!isAuthenticated) {
    return null; // Modal will be shown by AuthModalManager
  }

  
  // Explicitly check for customer role to prevent unexpected roles from accessing customer routes
  const isCustomer = userInfo?.role === 'customer';
  if (!isCustomer) {
    if (userInfo?.role === 'admin') {
      return <Navigate to="/admin/dashboard" replace />;
    } else if (userInfo?.role === 'staff') {
      return <Navigate to="/staff/dashboard" replace />;
    } else if (userInfo?.role === 'accountant') {
      return <Navigate to="/accountant/dashboard" replace />;
    }
    return <Navigate to="/" replace />;
  }

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

export default CustomerRoute;

