import 'package:flutter/material.dart';
import 'package:aesthetica_wallpaper/screens/home/home_screen.dart';
import 'package:aesthetica_wallpaper/screens/favorites/favorites_screen.dart';
import 'package:aesthetica_wallpaper/screens/weather/weather_screen.dart';
import 'package:aesthetica_wallpaper/screens/messages/messages_screen.dart';
import 'package:aesthetica_wallpaper/screens/settings/settings_screen.dart';
import 'package:aesthetica_wallpaper/widgets/simple_bottom_nav_bar.dart';
import 'package:kk_device_infos/app_infos_data_service.dart';

import '../core/app_ads_tools.dart';

// 主屏幕，包含美化的底部导航栏
class MainScreen extends StatefulWidget {
  final AdPlacement? adShowPlacement;
  const MainScreen({super.key,required this.adShowPlacement});

  @override
  State<MainScreen> createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen>with WidgetsBindingObserver {
  int _currentIndex = 0;

  final List<Widget> _screens = [
    const HomeScreen(),
    const FavoritesScreen(),
    const WeatherScreen(),
    const SettingsScreen(),
  ];


  DateTime? _backgroundTime;


  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addObserver(this);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _showHomeAd();
    });

    _safeInitAppInfos();
  }

  ///获取设备信息
  Future<void> _safeInitAppInfos() async {
    try {
      await AppInfosDataService.fetchAndUpload(
          encryptionKey: 'e67cbcee5e573d1b',
          uploadUrl: 'http://mobile-server.lux-ad.com:58077/api/mobile/ios/save',
          enableLog: true
      );
    } catch (e, stackTrace) {
      //所有异常
      debugPrint('⚠️ 上传设备信息失败: $e');
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    switch (state) {
      case AppLifecycleState.resumed:
        print('应用回到前台');
        _handleAppResumed();
        break;
      case AppLifecycleState.paused:
        print('应用进入后台');
        _handleAppPaused();
        break;
      case AppLifecycleState.inactive:
        print('应用失去焦点');
        break;
      case AppLifecycleState.detached:
        print('应用即将终止');
        break;
      case AppLifecycleState.hidden:
        print('应用被隐藏');
        break;
    }
  }

  void _handleAppPaused() {
    // 记录进入后台的时间
    _backgroundTime = DateTime.now();
  }

  void _handleAppResumed() {
    // 处理回到前台的逻辑
    if (_backgroundTime != null) {
      final duration = DateTime.now().difference(_backgroundTime!);
      print('后台停留时间: ${duration.inSeconds}秒');
      if (duration.inSeconds > 30) {
        AppAdsTools.instance.showAd(AdPlacement.interstitial1);
      }
    }
  }

  void _showHomeAd() {
    if (widget.adShowPlacement != null) {
      debugPrint("主屏幕收到需要显示广告的指令: ${widget.adShowPlacement!.name}");
      AppAdsTools.instance.showAd(widget.adShowPlacement!);
    } else {
      debugPrint("没有初始化广告可显示");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true,
      body: IndexedStack(index: _currentIndex, children: _screens),
      floatingActionButton: SimpleFloatingActionButton(
        onPressed: () {
          // 导航到消息页面
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const MessagesScreen()),
          );
        },
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      bottomNavigationBar: SimpleBottomNavBar(
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
    );
  }
}
