import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yumi/app/constants/sc_global_config.dart';
import 'package:yumi/shared/tools/sc_version_utils.dart';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:yumi/app/routes/sc_routes.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/shared/data_sources/sources/local/file_cache_manager.dart';
import 'package:yumi/modules/auth/login_route.dart';

class SplashPage extends StatefulWidget {
  const SplashPage({super.key});

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  static const Duration _minimumSplashDuration = Duration(milliseconds: 900);

  Timer? _timer;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      unawaited(FileCacheManager.getInstance().getFilePath());
    });
    _startNavigationTimer();
  }

  @override
  void dispose() {
    _cancelTimer();
    super.dispose();
  }

  /// 启动页最短展示时间
  void _startNavigationTimer() {
    _timer = Timer(_minimumSplashDuration, () {
      if (mounted) {
        _goMainPage();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Stack(
        alignment: Alignment.center,
        children: [
          Image.asset(
            SCGlobalConfig.businessLogicStrategy.getSplashPageBackgroundImage(),
            width: ScreenUtil().screenWidth,
            height: ScreenUtil().screenHeight,
            fit: BoxFit.cover,
          ),
          Image.asset(
            SCGlobalConfig.businessLogicStrategy.getSplashPageIcon(),
            width: 107.w,
            height: 159.w,
          ),
        ],
      ),
    );
  }

  void _goMainPage() async {
    try {
      await SCVersionUtils.checkReview();
      if (!mounted) {
        return;
      }
      var user = AccountStorage().getCurrentUser();
      var token = AccountStorage().getToken();
      if (user != null && token.isNotEmpty) {
        SCNavigatorUtils.push(context, SCRoutes.home, replace: true);
      } else {
        SCNavigatorUtils.push(context, LoginRouter.login, replace: true);
      }
    } catch (e) {
      if (!mounted) {
        return;
      }
      SCNavigatorUtils.push(context, LoginRouter.login, replace: true);
    }
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }
}
