import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '../stores/authStore';

interface AuthGuardProps {
  children: React.ReactNode;
  requiredPermissions?: {
    categoryId?: number;
    action: 'create' | 'edit' | 'delete';
  };
}

export function AuthGuard({ children, requiredPermissions }: AuthGuardProps) {
  const { user, loading } = useAuthStore();
  const location = useLocation();

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
      </div>
    );
  }

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

  if (requiredPermissions) {
    const { categoryId, action } = requiredPermissions;
    
    if (!user.permissions.isAdmin) {
      if (categoryId && !user.permissions.categories[categoryId]?.[action]) {
        return (
          <div className="min-h-screen flex items-center justify-center">
            <div className="text-center">
              <h2 className="text-2xl font-bold text-gray-900 mb-4">Access Denied</h2>
              <p className="text-gray-600">
                У вас нет прав на {action} статьи в разделе {categoryId}.
              </p>
            </div>
          </div>
        );
      }
    }
  }

  return <>{children}</>;
}