import React from 'react';
import { createBrowserRouter, Navigate } from 'react-router-dom';
import MainLayout from '../components/Layout';
import LoginPage from '../pages/Login';
import Dashboard from '../pages/Dashboard';
import DeviceTypePage from '../pages/DeviceType';
import BatchPage from '../pages/Batch';
import BatchDetail from '../pages/Batch/Detail';
import DevicePage from '../pages/Device';
import UserPage from '../pages/User';
import AdminPage from '../pages/Admin';
import { useAuthStore } from '../store/useAuthStore';

// 路由守卫组件
const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const { isAuthenticated } = useAuthStore();

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

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

// 创建路由
const router = createBrowserRouter([
    {
        path: '/login',
        element: <LoginPage />,
    },
    {
        path: '/',
        element: (
            <ProtectedRoute>
                <MainLayout />
            </ProtectedRoute>
        ),
        children: [
            {
                index: true,
                element: <Navigate to="/dashboard" replace />,
            },
            {
                path: 'dashboard',
                element: <Dashboard />,
            },
            {
                path: 'device-types',
                element: <DeviceTypePage />,
            },
            {
                path: 'batches',
                element: <BatchPage />,
            },
            {
                path: 'batches/:id',
                element: <BatchDetail />,
            },
            {
                path: 'devices',
                element: <DevicePage />,
            },
            {
                path: 'users',
                element: <UserPage />,
            },
            {
                path: 'admins',
                element: <AdminPage />,
            },
        ],
    },
    {
        path: '*',
        element: <Navigate to="/dashboard" replace />,
    },
]);

export default router;
