import 'package:flutter/material.dart';
import '../../../../app/theme/app_colors.dart';
import '../../../../app/router.dart';
import '../../../../app/i18n/app_localizations.dart';
import '../../../../core/services/auth_service.dart';
import '../../../../core/network/api_client.dart';
import '../../../../core/telemetry/telemetry_service.dart';

/// 发行方登录页
///
/// 企业账号登录：手机号+验证码 / 账号密码
/// 新发行方引导至入驻流程
class IssuerLoginPage extends StatefulWidget {
  const IssuerLoginPage({super.key});

  @override
  State<IssuerLoginPage> createState() => _IssuerLoginPageState();
}

class _IssuerLoginPageState extends State<IssuerLoginPage> {
  final _phoneController = TextEditingController();
  final _codeController = TextEditingController();
  bool _agreedToTerms = false;
  bool _isLoading = false;
  bool _isSendingCode = false;
  int _countdown = 0;
  String? _errorMessage;

  final _authService = AuthService();

  @override
  void initState() {
    super.initState();
    // 遥测服务初始化（在首帧渲染后采集设备信息）
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if (!TelemetryService().isInitialized) {
        await TelemetryService().initialize(
          apiBaseUrl: 'https://api.gogenex.cn',
          context: context,
        );
      }
    });
  }

  @override
  void dispose() {
    _phoneController.dispose();
    _codeController.dispose();
    super.dispose();
  }

  Future<void> _sendSmsCode() async {
    final phone = _phoneController.text.trim();
    if (phone.isEmpty) return;

    setState(() {
      _isSendingCode = true;
      _errorMessage = null;
    });

    try {
      await _authService.sendSmsCode(phone, type: SmsCodeType.login);
      if (!mounted) return;
      setState(() {
        _isSendingCode = false;
        _countdown = 60;
      });
      _startCountdown();
    } catch (e) {
      debugPrint('[IssuerLoginPage] sendSmsCode error: $e');
      if (!mounted) return;
      setState(() {
        _isSendingCode = false;
        _errorMessage = e.toString();
      });
    }
  }

  void _startCountdown() {
    Future.doWhile(() async {
      await Future.delayed(const Duration(seconds: 1));
      if (!mounted) return false;
      setState(() => _countdown--);
      return _countdown > 0;
    });
  }

  Future<void> _login() async {
    final phone = _phoneController.text.trim();
    final code = _codeController.text.trim();
    if (phone.isEmpty || code.isEmpty) return;

    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final result = await _authService.loginByPhone(phone, code);
      ApiClient.instance.setToken(result.accessToken);
      // 遥测：登录成功后注入 userId 和 token
      if (TelemetryService().isInitialized) {
        TelemetryService().setUserId(result.user?['id'] as String?);
        TelemetryService().setAccessToken(result.accessToken);
      }
      if (!mounted) return;
      Navigator.pushReplacementNamed(context, AppRouter.main);
    } catch (e) {
      debugPrint('[IssuerLoginPage] login error: $e');
      if (!mounted) return;
      setState(() {
        _isLoading = false;
        _errorMessage = e.toString();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.symmetric(horizontal: 24),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const SizedBox(height: 60),

              // Logo
              ClipRRect(
                borderRadius: BorderRadius.circular(14),
                child: Image.asset(
                  'assets/images/logo_icon.png',
                  width: 56,
                  height: 56,
                ),
              ),
              const SizedBox(height: 24),

              // Title
              Text(
                context.t('login_title'),
                style: const TextStyle(fontSize: 28, fontWeight: FontWeight.w700, color: AppColors.textPrimary),
              ),
              const SizedBox(height: 8),
              Text(
                context.t('login_subtitle'),
                style: const TextStyle(fontSize: 15, color: AppColors.textSecondary),
              ),
              const SizedBox(height: 40),

              // Error Message
              if (_errorMessage != null) ...[
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: AppColors.errorLight,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Row(
                    children: [
                      const Icon(Icons.error_outline, color: AppColors.error, size: 18),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          _errorMessage!,
                          style: const TextStyle(fontSize: 13, color: AppColors.error),
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 16),
              ],

              // Phone Input
              TextField(
                controller: _phoneController,
                keyboardType: TextInputType.phone,
                enabled: !_isLoading,
                decoration: InputDecoration(
                  labelText: context.t('login_phone'),
                  prefixIcon: const Icon(Icons.phone_outlined),
                  hintText: context.t('login_phone_hint'),
                ),
              ),
              const SizedBox(height: 16),

              // Verification Code
              Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: _codeController,
                      keyboardType: TextInputType.number,
                      enabled: !_isLoading,
                      decoration: InputDecoration(
                        labelText: context.t('login_code'),
                        prefixIcon: const Icon(Icons.lock_outline_rounded),
                      ),
                    ),
                  ),
                  const SizedBox(width: 12),
                  SizedBox(
                    height: 52,
                    child: OutlinedButton(
                      onPressed: (_isSendingCode || _countdown > 0 || _isLoading)
                          ? null
                          : _sendSmsCode,
                      child: _isSendingCode
                          ? const SizedBox(
                              width: 16,
                              height: 16,
                              child: CircularProgressIndicator(strokeWidth: 2),
                            )
                          : Text(
                              _countdown > 0
                                  ? '${_countdown}s'
                                  : context.t('login_get_code'),
                            ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 24),

              // Terms
              Row(
                children: [
                  Checkbox(
                    value: _agreedToTerms,
                    onChanged: _isLoading
                        ? null
                        : (v) => setState(() => _agreedToTerms = v ?? false),
                    activeColor: AppColors.primary,
                  ),
                  Expanded(
                    child: Text.rich(
                      TextSpan(
                        text: context.t('login_agree_prefix'),
                        style: const TextStyle(fontSize: 13, color: AppColors.textSecondary),
                        children: [
                          TextSpan(
                            text: context.t('login_agreement'),
                            style: const TextStyle(color: AppColors.primary),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 24),

              // Login Button
              SizedBox(
                width: double.infinity,
                height: 52,
                child: ElevatedButton(
                  onPressed: (_agreedToTerms && !_isLoading) ? _login : null,
                  child: _isLoading
                      ? const SizedBox(
                          width: 22,
                          height: 22,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            color: Colors.white,
                          ),
                        )
                      : Text(context.t('login_button'), style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
                ),
              ),
              const SizedBox(height: 16),

              // Register
              Center(
                child: TextButton(
                  onPressed: _isLoading
                      ? null
                      : () => Navigator.pushNamed(context, AppRouter.onboarding),
                  child: Text(context.t('login_register')),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
