import React from 'react';
import { Result, Button } from 'antd';
import { useNavigate } from 'react-router-dom';
import { findRoleAwareLandingPath } from '../auth/menu-policy';
import { usePermission } from '../hooks/usePermission';

interface PermissionRouteProps {
  permission: string;
  children: React.ReactNode;
}

const PermissionRoute: React.FC<PermissionRouteProps> = ({ permission, children }) => {
  const { permissions, hasPermission } = usePermission();
  const navigate = useNavigate();
  if (!hasPermission(permission)) {
    let roles: string[] = [];
    try {
      roles = JSON.parse(localStorage.getItem('user') || '{}').roles || [];
    } catch {
      roles = [];
    }
    const firstPath = findRoleAwareLandingPath(roles, permissions);
    return (
      <Result
        status="403"
        title="无权访问"
        subTitle="您没有访问此页面的权限"
        extra={
          firstPath ? (
            <Button type="primary" onClick={() => navigate(firstPath, { replace: true })}>
              前往可访问页面
            </Button>
          ) : undefined
        }
      />
    );
  }
  return <>{children}</>;
};

export default PermissionRoute;
