import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:provider/provider.dart';
import '../../../core/theme/app_spacing.dart';
import '../../../providers/auth_provider.dart';
import '../home/home_page.dart';
import '../market/market_page.dart';
import '../trade/trade_page.dart';
import '../asset/asset_page.dart';
import '../mine/mine_page.dart';

/// 底部导航项
class _NavItem {
  final String label;
  final IconData icon;
  final Widget page;

  const _NavItem({required this.label, required this.icon, required this.page});
}

/// 主页面 - "The Kinetic Vault" 设计风格
class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  int _currentIndex = 0;
  final Set<int> _loadedPages = {0};

  static final _navItems = [
    _NavItem(label: '行情', icon: LucideIcons.trendingUp, page: const MarketPage()),
    _NavItem(label: '交易', icon: LucideIcons.arrowLeftRight, page: const TradePage()),
    _NavItem(label: '资产', icon: LucideIcons.wallet, page: const AssetPage()),
    _NavItem(label: '我的', icon: LucideIcons.user, page: const MinePage()),
  ];

  void _onTabChanged(int index) {
    setState(() {
      _currentIndex = index;
      _loadedPages.add(index);
    });
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return Scaffold(
      backgroundColor: colorScheme.background,
      body: Column(
        children: [
          // 公共顶部导航栏
          const _TopAppBar(),
          // 页面内容
          Expanded(
            child: LazyIndexedStack(
              index: _currentIndex,
              loadedIndexes: _loadedPages,
              children: _navItems.map((item) => item.page).toList(),
            ),
          ),
        ],
      ),
      bottomNavigationBar: _BottomNavBar(
        items: _navItems,
        currentIndex: _currentIndex,
        onTap: _onTabChanged,
      ),
    );
  }
}

/// 顶部导航栏 - 玻璃拟态效果
class _TopAppBar extends StatelessWidget {
  const _TopAppBar();

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return Container(
      height: 64, // 顶部导航栏高度保持固定
      decoration: BoxDecoration(
        color: colorScheme.surfaceBright.withOpacity(0.4),
        boxShadow: [
          BoxShadow(
            color: colorScheme.primary.withOpacity(isDark ? 0.15 : 0.08),
            blurRadius: 64, // 大模糊效果保持固定
            offset: const Offset(0, 32),
          ),
        ],
      ),
      child: ClipRRect(
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: AppSpacing.xl, sigmaY: AppSpacing.xl),
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: AppSpacing.lg),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                // 左侧头像和标题
                Consumer<AuthProvider>(
                  builder: (context, auth, _) {
                    return Row(
                      children: [
                        // 头像
                        Container(
                          width: 32, // 头像尺寸保持固定
                          height: 32,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            border: Border.all(
                              color: colorScheme.outlineVariant.withOpacity(0.2),
                            ),
                          ),
                          child: CircleAvatar(
                            backgroundColor: colorScheme.surfaceContainerHigh,
                            child: Text(
                              auth.user?.avatarText ?? 'U',
                              style: TextStyle(
                                color: colorScheme.primary,
                                fontWeight: FontWeight.bold,
                                fontSize: 12,
                              ),
                            ),
                          ),
                        ),
                        SizedBox(width: AppSpacing.sm + AppSpacing.xs),
                        // 标题
                        Text(
                          '模拟所',
                          style: TextStyle(
                            color: colorScheme.primary,
                            fontWeight: FontWeight.w900,
                            letterSpacing: -0.5,
                            fontSize: 16,
                          ),
                        ),
                      ],
                    );
                  },
                ),
                // 右侧操作按钮
                Row(
                  children: [
                    _IconBtn(
                      icon: LucideIcons.search,
                      onTap: () {},
                    ),
                    SizedBox(width: AppSpacing.sm),
                    _IconBtn(
                      icon: LucideIcons.bell,
                      onTap: () {},
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

/// 图标按钮
class _IconBtn extends StatelessWidget {
  final IconData icon;
  final VoidCallback onTap;

  const _IconBtn({required this.icon, required this.onTap});

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.all(AppSpacing.sm),
        child: Icon(
          icon,
          color: colorScheme.onSurfaceVariant,
          size: 22,
        ),
      ),
    );
  }
}

/// 底部导航栏 - "The Kinetic Vault" 设计风格
class _BottomNavBar extends StatelessWidget {
  final List<_NavItem> items;
  final int currentIndex;
  final ValueChanged<int> onTap;

  const _BottomNavBar({
    required this.items,
    required this.currentIndex,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return Container(
      decoration: BoxDecoration(
        color: colorScheme.surfaceContainerLow.withOpacity(0.8),
        borderRadius: BorderRadius.vertical(top: Radius.circular(AppRadius.xxl + AppSpacing.sm)),
        border: Border(
          top: BorderSide(
            color: colorScheme.outlineVariant.withOpacity(0.15),
          ),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.5),
            blurRadius: 40, // 阴影效果保持固定
            offset: const Offset(0, -10),
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.vertical(top: Radius.circular(AppRadius.xxl + AppSpacing.sm)),
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: AppSpacing.md, sigmaY: AppSpacing.md),
          child: SafeArea(
            child: Padding(
              padding: EdgeInsets.fromLTRB(AppSpacing.md, AppSpacing.sm, AppSpacing.md, AppSpacing.lg),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: items.asMap().entries.map((entry) {
                  return _NavItemWidget(
                    item: entry.value,
                    isSelected: entry.key == currentIndex,
                    onTap: () => onTap(entry.key),
                  );
                }).toList(),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

/// 导航项组件
class _NavItemWidget extends StatelessWidget {
  final _NavItem item;
  final bool isSelected;
  final VoidCallback onTap;

  const _NavItemWidget({
    required this.item,
    required this.isSelected,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    final color = isSelected ? colorScheme.primary : colorScheme.onSurfaceVariant;

    return GestureDetector(
      onTap: onTap,
      behavior: HitTestBehavior.opaque,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        padding: EdgeInsets.symmetric(horizontal: AppSpacing.md, vertical: AppSpacing.sm),
        decoration: isSelected
            ? BoxDecoration(
                color: colorScheme.primary.withOpacity(0.1),
                borderRadius: BorderRadius.circular(AppSpacing.md),
                boxShadow: [
                  BoxShadow(
                    color: colorScheme.primary.withOpacity(0.3),
                    blurRadius: 15, // 发光效果保持固定
                    spreadRadius: 0,
                  ),
                ],
              )
            : null,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              item.icon,
              color: color,
              size: 24,
            ),
            SizedBox(height: AppSpacing.xs),
            Text(
              item.label,
              style: TextStyle(
                color: color,
                fontSize: 12,
                fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// 懒加载 IndexedStack - 只渲染已访问过的页面
class LazyIndexedStack extends StatefulWidget {
  final int index;
  final Set<int> loadedIndexes;
  final List<Widget> children;

  const LazyIndexedStack({
    super.key,
    required this.index,
    required this.loadedIndexes,
    required this.children,
  });

  @override
  State<LazyIndexedStack> createState() => _LazyIndexedStackState();
}

class _LazyIndexedStackState extends State<LazyIndexedStack> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: widget.children.asMap().entries.map((entry) {
        final isVisible = entry.key == widget.index;
        final isLoaded = widget.loadedIndexes.contains(entry.key);

        return Positioned.fill(
          child: Offstage(
            offstage: !isVisible,
            child: TickerMode(
              enabled: isVisible,
              child: isLoaded ? entry.value : const SizedBox.shrink(),
            ),
          ),
        );
      }).toList(),
    );
  }
}
