import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import '../../core/i18n/app_localizations.dart';
import 'nav_bar_config.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_colors_extension.dart';

class AppShell extends ConsumerStatefulWidget {
  final Widget child;
  const AppShell({super.key, required this.child});

  @override
  ConsumerState<AppShell> createState() => _AppShellState();
}

class _AppShellState extends ConsumerState<AppShell> {
  final _tabRoutes = ['/messages', '/', '/profile'];

  bool _showBottomBar(String location) {
    return location == '/' || location == '/messages' || location == '/profile';
  }

  int _tabIndex(String location) {
    if (location.startsWith('/messages')) return 0;
    if (location == '/' || !location.startsWith('/profile')) return 1;
    return 2;
  }

  NavBarConfig _rootConfig(String location, AppLocalizations l10n) {
    if (location.startsWith('/messages')) {
      return NavBarConfig(
        title: l10n.get('tabMessages'),
        showBack: true,
        leadingIcon: Icons.close,
      );
    }
    if (location == '/') {
      return NavBarConfig(
        title: l10n.get('appName'),
        showBack: true,
        leadingIcon: Icons.close,
      );
    }
    if (location.startsWith('/profile')) {
      return NavBarConfig(
        title: l10n.get('tabProfile'),
        showBack: true,
        leadingIcon: Icons.close,
      );
    }
    return NavBarConfig.home;
  }

  @override
  Widget build(BuildContext context) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    final location = GoRouterState.of(context).uri.toString();

    // 更新路由记忆：当前 Tab 的最后位置
    final tabIndex = _tabIndex(location);
    if (_tabRoutes[tabIndex] != location && _showBottomBar(location)) {
      _tabRoutes[tabIndex] = location;
    }

    final showBottomBar = _showBottomBar(location);
    final config = showBottomBar
        ? _rootConfig(location, l10n)
        : ref.watch(navBarConfigProvider);

    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(
        statusBarColor: colors.bgCard,
        statusBarIconBrightness: Brightness.dark,
        statusBarBrightness: Brightness.light,
      ),
    );

    return Scaffold(
      backgroundColor: colors.bgPage,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          _buildNavBar(config, location, context),
          Expanded(child: widget.child),
          if (showBottomBar) _buildBottomBar(location, context, l10n),
        ],
      ),
    );
  }

  Widget _buildNavBar(
    NavBarConfig config,
    String location,
    BuildContext context,
  ) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final isRoot = _showBottomBar(location);

    List<TDNavBarItem>? leftItems;
    if (config.showBack) {
      final icon = config.leadingIcon ?? TDIcons.chevron_left;
      leftItems = [
        TDNavBarItem(
          icon: icon,
          iconSize: 22,
          iconColor: colors.textPrimary,
          action:
              config.onBack ??
              (isRoot
                  ? () => SystemNavigator.pop()
                  : () => GoRouter.of(context).pop()),
        ),
      ];
    }

    List<TDNavBarItem>? rightItems;
    if (config.showRight && config.rightWidget != null) {
      rightItems = [TDNavBarItem(iconWidget: config.rightWidget, iconSize: 22)];
    }

    return TDNavBar(
      title: config.title,
      titleColor: colors.textPrimary,
      titleFontWeight: FontWeight.w600,
      titleFont: Font(size: AppFontSizes.title.toInt(), lineHeight: 26),
      backgroundColor: colors.bgCard,
      height: 56,
      centerTitle: true,
      useDefaultBack: false,
      screenAdaptation: true,
      leftBarItems: leftItems,
      rightBarItems: rightItems,
    );
  }

  Widget _buildBottomBar(
    String location,
    BuildContext context,
    AppLocalizations l10n,
  ) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    return LayoutBuilder(
      builder: (ctx, constraints) {
        if (constraints.maxWidth <= 0) {
          return const SizedBox.shrink();
        }
        final bottomPadding = MediaQuery.of(ctx).padding.bottom;
        return Padding(
          padding: EdgeInsets.only(top: 8, bottom: 8 + bottomPadding),
          child: TDBottomTabBar(
            TDBottomTabBarBasicType.iconText,
            useSafeArea: false,
            componentType: TDBottomTabBarComponentType.label,
            outlineType: TDBottomTabBarOutlineType.capsule,
            currentIndex: _tabIndex(location),
            navigationTabs: [
              TDBottomTabBarTabConfig(
                tabText: l10n.get('tabMessages'),
                selectedIcon: Icon(
                  Icons.notifications,
                  size: 22,
                  color: colors.primary,
                ),
                unselectedIcon: Icon(
                  Icons.notifications_outlined,
                  size: 22,
                  color: colors.textSecondary,
                ),
                selectTabTextStyle: TextStyle(
                  fontSize: 10,
                  fontWeight: FontWeight.w600,
                  color: colors.primary,
                ),
                unselectTabTextStyle: TextStyle(
                  fontSize: 10,
                  color: colors.textSecondary,
                ),
                onTap: () => context.go(_tabRoutes[0]),
              ),
              TDBottomTabBarTabConfig(
                tabText: l10n.get('tabWorkbench'),
                selectedIcon: Icon(
                  Icons.dashboard,
                  size: 22,
                  color: colors.primary,
                ),
                unselectedIcon: Icon(
                  Icons.dashboard_outlined,
                  size: 22,
                  color: colors.textSecondary,
                ),
                selectTabTextStyle: TextStyle(
                  fontSize: 10,
                  fontWeight: FontWeight.w600,
                  color: colors.primary,
                ),
                unselectTabTextStyle: TextStyle(
                  fontSize: 10,
                  color: colors.textSecondary,
                ),
                onTap: () => context.go(_tabRoutes[1]),
              ),
              TDBottomTabBarTabConfig(
                tabText: l10n.get('tabProfile'),
                selectedIcon: Icon(
                  Icons.person,
                  size: 22,
                  color: colors.primary,
                ),
                unselectedIcon: Icon(
                  Icons.person_outline,
                  size: 22,
                  color: colors.textSecondary,
                ),
                selectTabTextStyle: TextStyle(
                  fontSize: 10,
                  fontWeight: FontWeight.w600,
                  color: colors.primary,
                ),
                unselectTabTextStyle: TextStyle(
                  fontSize: 10,
                  color: colors.textSecondary,
                ),
                onTap: () => context.go(_tabRoutes[2]),
              ),
            ],
          ),
        );
      },
    );
  }
}
