import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/router/routes.dart';
import '../../../core/config/environment.dart';
import '../../../core/telemetry/telemetry_service.dart';
import '../../providers/user_providers.dart';

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

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

class _SplashPageState extends ConsumerState<SplashPage> {
  // 设计色彩 - 与导航页面统一
  static const Color _orange = Color(0xFFFF6B00);
  static const Color _darkText = Color(0xFF1F2937);
  static const Color _grayText = Color(0xFF6B7280);
  static const Color _serenade = Color(0xFFFFF7ED);

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

  Future<void> _initialize() async {
    // 最多等 500ms 展示品牌，然后立即跳转，不阻塞用户
    await Future.delayed(const Duration(milliseconds: 500));

    if (!mounted) return;

    final userState = ref.read(userNotifierProvider);

    // 初始化遥测服务（非阻塞，异常不影响主流程）
    TelemetryService().initialize(
      apiBaseUrl: EnvironmentConfig.baseUrl,
      context: context,
      userId: userState.isLoggedIn ? userState.accountSequence : null,
    ).then((_) {
      if (userState.isLoggedIn && userState.accessToken != null) {
        TelemetryService().setAccessToken(userState.accessToken);
      }
    }).catchError((e) {
      debugPrint('[Telemetry] Initialize failed (non-blocking): $e');
    });

    if (userState.isLoggedIn) {
      // 已登录，直接跳转，不需要主动刷新 token
      // token 刷新只在 API 返回 401 时才触发
      if (mounted) {
        context.go(Routes.trading);
      }
    } else {
      if (mounted) context.go(Routes.login);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 100,
              height: 100,
              decoration: BoxDecoration(
                color: _serenade,
                borderRadius: BorderRadius.circular(24),
              ),
              child: const Icon(
                Icons.eco,
                size: 60,
                color: _orange,
              ),
            ),
            const SizedBox(height: 24),
            const Text(
              '股行',
              style: TextStyle(
                color: _darkText,
                fontSize: 28,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8),
            const Text(
              '绿色财富 共享未来',
              style: TextStyle(
                color: _grayText,
                fontSize: 16,
              ),
            ),
            const SizedBox(height: 48),
            const SizedBox(
              width: 24,
              height: 24,
              child: CircularProgressIndicator(
                color: _orange,
                strokeWidth: 2,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
