import { Navigate, Outlet, useLocation } from 'react-router-dom';
import { useEffect } from 'react';
import { Skeleton } from 'antd';

import { useUserStore } from '@/stores/user';
import { usePermissionStore } from '@/stores/permission';

export default function AuthGuard() {
  const token = useUserStore(s => s.token);
  const location = useLocation();
  const menusLoaded = usePermissionStore(s => s.menusLoaded);
  const getMenus = usePermissionStore(s => s.getMenus);

  useEffect(() => {
    if (token && !menusLoaded) {
      getMenus();
    }
  }, [token, getMenus, menusLoaded]);

  if (!token) return <Navigate to={`/login?redirect=${location.pathname}`} replace />;
  if (!menusLoaded) {
    return (
      <div style={{ padding: 48, maxWidth: 480 }}>
        <Skeleton active paragraph={{ rows: 6 }} />
      </div>
    );
  }

  return <Outlet />;
}
