import React, { useState } from 'react';
import { HashRouter, Routes, Route, Navigate, useLocation, Outlet } from 'react-router-dom';
import { AnimatePresence, motion } from 'framer-motion';
import { AuthProvider } from './contexts/AuthContext';
import { ErrorBoundary, PageErrorBoundary } from './components/ErrorBoundary';
import { LoginPage } from './pages/LoginPage';
import { RegisterPage } from './pages/RegisterPage';
import { RoleSelectPage } from './pages/RoleSelectPage';
import { PurchaserDashboard } from './pages/purchaser/Dashboard';
import { TextileDashboard } from './pages/textile/Dashboard';
import { WashingDashboard } from './pages/washing/Dashboard';
import { WashingPlanOverview } from './pages/washing/PlanOverview';
import { FinishedWarehouse } from './pages/washing/FinishedWarehouse';
import { PendingFabric } from './pages/washing/PendingFabric';
import { CompletedFabric } from './pages/washing/CompletedFabric';
import { WashingPaymentPending } from './pages/washing/PaymentPending';
import { PlanOverview } from './pages/purchaser/PlanOverview';
import { NewPlan } from './pages/purchaser/NewPlan';
import { WarehouseManage } from './pages/purchaser/WarehouseManage';
import { FactoryManage } from './pages/purchaser/FactoryManage';
import { AccountsPayable } from './pages/purchaser/AccountsPayable';
import { NewWashingPlan } from './pages/purchaser/NewWashingPlan';
import { FinishedWarehouse as PurchaserFinishedWarehouse } from './pages/purchaser/FinishedWarehouse';
import { MemberManage } from './pages/MemberManage';
import { TextilePlanOverview } from './pages/textile/PlanOverview';
import { YarnWarehouse } from './pages/textile/YarnWarehouse';
import { FabricWarehouse } from './pages/textile/FabricWarehouse';
import { PaymentPending } from './pages/textile/PaymentPending';
import { ImportPlanPage } from './pages/ImportPlanPage';
import { DemoDataSharing } from './pages/DemoDataSharing';
import { DemoDisclaimerModal } from './components/DemoDisclaimerModal';
import { NetworkStatusBar } from './components/NetworkStatusBar';
import { DemoWatermark } from './components/DemoWatermark';
import { DataIntegrityDashboard } from './components/DataIntegrityDashboard';
import { PurchaserLayout } from './components/layout/PurchaserLayout';
import { TextileLayout } from './components/layout/TextileLayout';
import { WashingLayout } from './components/layout/WashingLayout';
import { RoleGuard } from './components/RoleGuard';
import './styles/index.css';

// 页面过渡动画配置
const pageTransitionVariants = {
  initial: {
    opacity: 0,
    y: 20,
    scale: 0.98,
  },
  animate: {
    opacity: 1,
    y: 0,
    scale: 1,
    transition: {
      duration: 0.35,
      ease: [0.25, 0.46, 0.45, 0.94],
    },
  },
  exit: {
    opacity: 0,
    y: -10,
    scale: 0.98,
    transition: {
      duration: 0.25,
      ease: [0.25, 0.46, 0.45, 0.94],
    },
  },
};

// 带动画的页面包装组件
function AnimatedRoute({ children, pageName }: { children: React.ReactNode; pageName?: string }) {
  return (
    <motion.div
      variants={pageTransitionVariants}
      initial="initial"
      animate="animate"
      exit="exit"
      style={{ willChange: 'transform, opacity' }}
    >
      <PageErrorBoundary pageName={pageName}>
        {children}
      </PageErrorBoundary>
    </motion.div>
  );
}

// 路由配置组件
function AppRoutes() {
  const location = useLocation();

  return (
    <AnimatePresence mode="wait">
      <Routes location={location} key={location.pathname}>
        {/* 公共路由 */}
        <Route path="/login" element={<AnimatedRoute pageName="登录"><LoginPage /></AnimatedRoute>} />
        <Route path="/register" element={<AnimatedRoute pageName="注册"><RegisterPage /></AnimatedRoute>} />
        <Route path="/role-select" element={<AnimatedRoute pageName="角色选择"><RoleSelectPage /></AnimatedRoute>} />

        {/* 采购商路由 - RoleGuard + PurchaserLayout */}
        <Route element={<RoleGuard allowedRoles={['purchaser']} />}>
          <Route path="/purchaser" element={<PurchaserLayout />}>
            <Route index element={<AnimatedRoute pageName="采购商首页"><PurchaserDashboard /></AnimatedRoute>} />
            <Route path="plans" element={<AnimatedRoute pageName="计划总览"><PlanOverview /></AnimatedRoute>} />
            <Route path="plans/new" element={<AnimatedRoute pageName="新建计划"><NewPlan /></AnimatedRoute>} />
            <Route path="warehouse" element={<AnimatedRoute pageName="生产仓库管理"><WarehouseManage /></AnimatedRoute>} />
            <Route path="factories" element={<AnimatedRoute pageName="工厂管理"><FactoryManage /></AnimatedRoute>} />
            <Route path="accounts-payable" element={<AnimatedRoute pageName="应付账款"><AccountsPayable /></AnimatedRoute>} />
            <Route path="washing-plans/new" element={<AnimatedRoute pageName="新建水洗计划"><NewWashingPlan /></AnimatedRoute>} />
            <Route path="finished-warehouse" element={<AnimatedRoute pageName="成品仓库"><PurchaserFinishedWarehouse /></AnimatedRoute>} />
          </Route>
        </Route>

        {/* 纺织厂路由 - RoleGuard + TextileLayout */}
        <Route element={<RoleGuard allowedRoles={['textile']} />}>
          <Route path="/textile" element={<TextileLayout />}>
            <Route index element={<AnimatedRoute pageName="纺织厂首页"><TextileDashboard /></AnimatedRoute>} />
            <Route path="plans" element={<AnimatedRoute pageName="纺织厂计划"><TextilePlanOverview /></AnimatedRoute>} />
            <Route path="fabric-warehouse" element={<AnimatedRoute pageName="坯布仓库"><FabricWarehouse /></AnimatedRoute>} />
            <Route path="yarn-warehouse" element={<AnimatedRoute pageName="纱线仓库"><YarnWarehouse /></AnimatedRoute>} />
            <Route path="payments" element={<AnimatedRoute pageName="待结款"><PaymentPending /></AnimatedRoute>} />
          </Route>
        </Route>

        {/* 水洗厂路由 - RoleGuard + WashingLayout */}
        <Route element={<RoleGuard allowedRoles={['washing']} />}>
          <Route path="/washing" element={<WashingLayout />}>
            <Route index element={<AnimatedRoute pageName="水洗厂首页"><WashingDashboard /></AnimatedRoute>} />
            <Route path="plans" element={<AnimatedRoute pageName="水洗计划管理"><WashingPlanOverview /></AnimatedRoute>} />
            <Route path="pending" element={<AnimatedRoute pageName="待处理坯布"><PendingFabric /></AnimatedRoute>} />
            <Route path="completed" element={<AnimatedRoute pageName="已完成坯布"><CompletedFabric /></AnimatedRoute>} />
            <Route path="finished-warehouse" element={<AnimatedRoute pageName="成品仓库"><FinishedWarehouse /></AnimatedRoute>} />
            <Route path="payments" element={<AnimatedRoute pageName="待结款"><WashingPaymentPending /></AnimatedRoute>} />
          </Route>
        </Route>

        {/* 子账号管理路由（所有已登录角色共用） */}
        <Route element={<RoleGuard allowedRoles={['purchaser', 'textile', 'washing']} />}>
          <Route path="/members" element={<AnimatedRoute pageName="子账号管理"><MemberManage /></AnimatedRoute>} />
        </Route>

        {/* 导入计划路由 */}
        <Route path="/import" element={<AnimatedRoute pageName="导入计划"><ImportPlanPage /></AnimatedRoute>} />

        {/* 数据共享演示路由 */}
        <Route path="/demo/data-sharing" element={<AnimatedRoute pageName="数据共享演示"><DemoDataSharing /></AnimatedRoute>} />

        {/* 数据完整性监控面板（管理员功能） */}
        <Route path="/admin/data-integrity" element={<AnimatedRoute pageName="数据完整性监控"><DataIntegrityDashboard /></AnimatedRoute>} />

        {/* 默认路由 */}
        <Route path="/" element={<Navigate to="/login" replace />} />
      </Routes>
    </AnimatePresence>
  );
}

function App() {
  return (
    <ErrorBoundary>
      <AuthProvider>
        <HashRouter>
          <NetworkStatusBar />
          <DemoDisclaimerModal />
          <AppRoutes />
          <DemoWatermark />
        </HashRouter>
      </AuthProvider>
    </ErrorBoundary>
  );
}

export default App;
