import React, { useEffect, useRef } from 'react';
import { useLocation, useNavigate } from 'react-router';
import { Result, Spin } from 'antd';
import { usePermission } from '../hooks/usePermission';
import { findRoleAwareLandingPath } from '../auth/menu-policy';
import { useUserStore } from '../store/user/userStore';

const DefaultRoute: React.FC = () => {
  const { permissions, permissionsReady } = usePermission();
  const roles = useUserStore((state) => state.user?.roles ?? []);
  const navigate = useNavigate();
  const { pathname } = useLocation();
  const firstPath = permissionsReady ? findRoleAwareLandingPath(roles, permissions) : null;

  // 用 effect 导航替代声明式 <Navigate>：RouteKeeper 会把首页（index）节点保活缓存，
  // 声明式 <Navigate> 在缓存节点随路由变化重渲染时会反复触发，导致首次进入系统后
  // 点击任何按钮都被拉回 dashboard，必须刷新页面才能恢复。这里仅在确实处于首页
  // 且已计算出落点时跳转；navigate 通过 ref 持有，避免其每次渲染变化导致 effect 空转。
  const navigateRef = useRef(navigate);
  navigateRef.current = navigate;
  useEffect(() => {
    if (pathname === '/' && firstPath) {
      navigateRef.current(firstPath, { replace: true });
    }
  }, [pathname, firstPath]);

  if (!permissionsReady) {
    return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;
  }
  if (!firstPath) {
    return (
      <Result status="403" title="暂无可访问功能" subTitle="请联系管理员为当前账号分配功能权限" />
    );
  }
  return null;
};

export default DefaultRoute;
