// main_page.dart
import 'package:flutter/material.dart';
import 'package:qhd_prevention/pages/badge_manager.dart';
import 'package:qhd_prevention/pages/home/scan_page.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import '../customWidget/nfc_test_page.dart';
import 'home/home_page.dart';
import 'app/application_page.dart';
import 'mine/mine_page.dart';
import 'notif/notif_page.dart';

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  int _currentIndex = 0;
  final GlobalKey<HomePageState> _homeKey = GlobalKey<HomePageState>();
  late final List<Widget> _pages;

  final List<String> _titles = ['首页', '应用中心', '通知公告', '我的'];

  @override
  void initState() {
    super.initState();
    _pages = <Widget>[
      HomePage(key: _homeKey),
      const ApplicationPage(),
      const NotifPage(),
      const MinePage(),
    ];
    // 监听 BadgeManager，当角标变化时 setState 刷新 UI
    BadgeManager().addListener(_onBadgeChanged);
  }

  @override
  void dispose() {
    BadgeManager().removeListener(_onBadgeChanged);
    super.dispose();
  }

  void _onBadgeChanged() {
    setState(() {
      // 只是为了重建，让 build 里拿到最新的 appCount / notifCount
    });
  }
  void _onScanPressed() {
    final homeState = _homeKey.currentState;
    if (homeState != null) {
      try {
        // 尝试调用 startScan()，如果 HomePageState 中实现了这个方法就会执行
        (homeState as dynamic).startScan();
        return;
      } catch (e) {
        // 如果调用失败则 fallback（打开 ScanPage）
        debugPrint('调用 HomePage.startScan 失败: $e');
      }
    }

  }
  Widget _buildIconWithBadge({required Widget icon, required int badgeCount}) {
    if (badgeCount <= 0) return icon;
    return Stack(
      clipBehavior: Clip.none,
      children: [
        icon,
        Positioned(
          right: -12,
          top: -4,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1),
            decoration: BoxDecoration(
              color: Colors.red,
              borderRadius: BorderRadius.circular(8),
            ),
            constraints: const BoxConstraints(minWidth: 16, minHeight: 16),
            child: Center(
              child: Text(
                '$badgeCount',
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 11,
                  height: 1,
                ),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    final bm = BadgeManager();
    return Scaffold(
      appBar:
          _currentIndex == 1
              ? null
              : MyAppbar(
                title: _currentIndex == 0 ? "智守安全首页" : _titles[_currentIndex],
                backgroundColor: Colors.blue,
                isBack: false,
                actions: [
                  if (_currentIndex == 0) ...[
                    IconButton(
                      onPressed: _onScanPressed,
                      // => Navigator.push(
                      //   context,
                      //   MaterialPageRoute(builder: (_) => ScanPage(totalList: [])),
                      // ),
                      icon: Image.asset(
                        "assets/images/scan.png",
                        width: 20,
                        height: 20,
                      ),
                    ),
                  ],
                ],
              ),
      body: _pages[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.fixed,
        selectedItemColor: Colors.blue,
        unselectedItemColor: Colors.grey,
        onTap: (i) {
          setState(() => _currentIndex = i);
          // 切到“应用”或“通知”标签时，按需拉最新角标
          if (i == 1) BadgeManager().updateAppCount();
          if (i == 2) BadgeManager().updateNotifCount();
        },
        items: [
          BottomNavigationBarItem(
            icon: Image.asset(
              'assets/tabbar/basics.png',
              width: 24,
              height: 24,
            ),
            activeIcon: Image.asset(
              'assets/tabbar/basics_cur.png',
              width: 24,
              height: 24,
            ),
            label: '首页',
          ),
          BottomNavigationBarItem(
            icon: _buildIconWithBadge(
              icon: Image.asset(
                'assets/tabbar/application.png',
                width: 24,
                height: 24,
              ),
              badgeCount: bm.appCount,
            ),
            activeIcon: _buildIconWithBadge(
              icon: Image.asset(
                'assets/tabbar/application_cur.png',
                width: 24,
                height: 24,
              ),
              badgeCount: bm.appCount,
            ),
            label: '应用',
          ),
          BottomNavigationBarItem(
            icon: _buildIconWithBadge(
              icon: Image.asset(
                'assets/tabbar/works.png',
                width: 24,
                height: 24,
              ),
              badgeCount: bm.notifCount,
            ),
            activeIcon: _buildIconWithBadge(
              icon: Image.asset(
                'assets/tabbar/works_cur.png',
                width: 24,
                height: 24,
              ),
              badgeCount: bm.notifCount,
            ),
            label: '通知',
          ),
          BottomNavigationBarItem(
            icon: Image.asset('assets/tabbar/my.png', width: 24, height: 24),
            activeIcon: Image.asset(
              'assets/tabbar/my_cur.png',
              width: 24,
              height: 24,
            ),
            label: '我的',
          ),
        ],
      ),
    );
  }
}
