import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAuth } from '@/contexts/AuthContext';
import { usePermissions } from '@/hooks/usePermissions';
import { Permission, Role } from '@/types/permissions';

export interface ProtectedRouteProps {
  children: React.ReactNode;
  requiredRole?: Role;
  permission?: Permission | Permission[];
  requireAll?: boolean;
  fallbackPath?: string;
}

/**
 * Enhanced protected route with role and permission checking
 */
const ProtectedRoute = ({
  children,
  requiredRole = 'user',
  permission,
  requireAll = false,
  fallbackPath = '/',
}: ProtectedRouteProps) => {
  const { isAuthenticated, isLoading } = useAuth();
  const { checkAnyPermission, checkAllPermissions, role } = usePermissions();
  const location = useLocation();

  if (isLoading) {
    return (
      <div className="flex h-screen w-full items-center justify-center bg-background">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  if (!isAuthenticated) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  // Check role
  if (requiredRole === 'admin' && role !== 'admin') {
    return <Navigate to={fallbackPath} replace />;
  }

  if (requiredRole === 'content_manager' && !['admin', 'content_manager'].includes(role)) {
    return <Navigate to={fallbackPath} replace />;
  }

  // Check permissions if specified
  if (permission) {
    const permissions = Array.isArray(permission) ? permission : [permission];
    const hasAccess = requireAll
      ? checkAllPermissions(permissions)
      : checkAnyPermission(permissions);

    if (!hasAccess) {
      return <Navigate to={fallbackPath} replace />;
    }
  }

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

export default ProtectedRoute;
