import 'package:autosos_flutter/config/theme_colors.dart';
import 'package:autosos_flutter/pages/splash/agreement_dialog.dart';
import 'package:autosos_flutter/provider/providers.dart';
import 'package:autosos_flutter/router/app_router.dart';
import 'package:autosos_flutter/service/location_service.dart';
import 'package:autosos_flutter/util/sp_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:permission_handler/permission_handler.dart';

/// 启动页（对应 Android SplashActivity）
class SplashPage extends ConsumerStatefulWidget {
  const SplashPage({super.key});

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

class _SplashPageState extends ConsumerState<SplashPage> {
  final String _pushType = '0';

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) => _bootstrap());
  }

  Future<void> _bootstrap() async {
    // 读取推送 type 参数
    // (真实使用中可以从 notification 启动 Intent 拿到)

    final agreed = SPUtil().get<bool>('isAgreement') ?? false;
    if (!agreed) {
      final ok = await showAgreementDialog(context);
      if (ok != true) return;
      SPUtil().setBool('isAgreement', true);
    }

    // 请求定位权限
    final locGranted = await _requestLocation();
    if (!locGranted) {
      // 提示去设置
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('请到设置中开启位置权限')),
        );
      }
      return;
    }

    _navigateNext();
  }

  Future<bool> _requestLocation() async {
    final status = await Permission.locationWhenInUse.request();
    if (!status.isGranted) return false;
    // 后台定位（Android 10+ 需要）
    if (await Permission.locationAlways.isDenied) {
      await Permission.locationAlways.request();
    }
    await LocationService.instance.init();
    LocationService.instance.start();
    return true;
  }

  void _navigateNext() {
    final logged = ref.read(isLoggedInProvider);
    final welcomed = SPUtil().get<bool>('isWelcome') ?? false;

    if (!logged) {
      context.go(Routes.login);
    } else if (!welcomed) {
      context.go(Routes.welcome);
    } else {
      _routeByPushType();
    }
  }

  void _routeByPushType() {
    final logged = ref.read(isLoggedInProvider);
    if (!logged) {
      context.go(Routes.login);
      return;
    }
    switch (_pushType) {
      case '1':
        context.go(Routes.orderWaiting);
        break;
      case '2':
        context.go(Routes.messenger);
        break;
      default:
        context.go(Routes.home);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeColors.primary,
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Image.asset(
              'images/1.5x/ic_launcher.png',
              width: 96,
              height: 96,
            ),
            const SizedBox(height: 16),
            const Text(
              '啾啾救援',
              style: TextStyle(color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
            const Text(
              '宁波易到互联科技有限公司',
              style: TextStyle(color: Colors.white70, fontSize: 12),
            ),
            const SizedBox(height: 32),
            const CircularProgressIndicator(color: Colors.white, strokeWidth: 2),
          ],
        ),
      ),
    );
  }
}