import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/account_service.dart';
import '../../../../routes/route_paths.dart';

/// 手机号注册页面参数
class PhoneRegisterParams {
  final String? inviterReferralCode; // 邀请人推荐码（可选）

  PhoneRegisterParams({this.inviterReferralCode});
}

/// 手机号注册页面
/// 输入手机号，发送验证码，跳转到验证码验证页面
class PhoneRegisterPage extends ConsumerStatefulWidget {
  final String? inviterReferralCode;

  const PhoneRegisterPage({
    super.key,
    this.inviterReferralCode,
  });

  @override
  ConsumerState<PhoneRegisterPage> createState() => _PhoneRegisterPageState();
}

class _PhoneRegisterPageState extends ConsumerState<PhoneRegisterPage> {
  final TextEditingController _phoneController = TextEditingController();
  final FocusNode _phoneFocusNode = FocusNode();

  bool _isSending = false;
  String? _errorMessage;

  // 倒计时
  int _countdown = 0;
  Timer? _countdownTimer;
  bool _canSend = true;

  @override
  void initState() {
    super.initState();
    debugPrint('[PhoneRegisterPage] initState - inviterReferralCode: ${widget.inviterReferralCode}');
    _phoneController.addListener(_onPhoneChanged);
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    _phoneController.removeListener(_onPhoneChanged);
    _phoneController.dispose();
    _phoneFocusNode.dispose();
    super.dispose();
  }

  void _startCountdown() {
    _countdown = 60;
    _canSend = false;
    _countdownTimer?.cancel();
    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countdown > 0) {
        setState(() {
          _countdown--;
        });
      } else {
        setState(() {
          _canSend = true;
        });
        timer.cancel();
      }
    });
  }

  void _onPhoneChanged() {
    // 手机号变化时更新按钮状态
    setState(() {
      if (_errorMessage != null) {
        _errorMessage = null;
      }
    });
  }

  /// 验证手机号格式
  bool _isValidPhoneNumber(String phone) {
    // 中国大陆手机号：1开头，第二位3-9，共11位
    final regex = RegExp(r'^1[3-9]\d{9}$');
    return regex.hasMatch(phone);
  }

  /// 发送验证码并跳转
  Future<void> _sendSmsCode() async {
    final phone = _phoneController.text.trim();

    // 验证手机号格式
    if (!_isValidPhoneNumber(phone)) {
      setState(() {
        _errorMessage = '请输入正确的手机号';
      });
      return;
    }

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

    try {
      final accountService = ref.read(accountServiceProvider);

      // 验证推荐码（如果有）
      if (widget.inviterReferralCode != null &&
          widget.inviterReferralCode!.isNotEmpty) {
        debugPrint('[PhoneRegisterPage] 验证推荐码: ${widget.inviterReferralCode}');
        await accountService.verifyReferralCode(widget.inviterReferralCode!);
        debugPrint('[PhoneRegisterPage] 推荐码验证通过');
      }

      // 发送验证码
      debugPrint('[PhoneRegisterPage] 发送验证码...');
      await accountService.sendSmsCode(phone, SmsCodeType.register);
      debugPrint('[PhoneRegisterPage] 验证码已发送');

      if (!mounted) return;

      // 启动倒计时
      _startCountdown();

      // 跳转到验证码页面
      context.push(
        RoutePaths.smsVerify,
        extra: SmsVerifyParams(
          phoneNumber: phone,
          type: SmsCodeType.register,
          inviterReferralCode: widget.inviterReferralCode,
        ),
      );
    } catch (e) {
      debugPrint('[PhoneRegisterPage] 发送验证码失败: $e');
      if (mounted) {
        setState(() {
          _errorMessage = e.toString().replaceAll('Exception: ', '');
        });
      }
    } finally {
      if (mounted) {
        setState(() {
          _isSending = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Color(0xFF333333)),
          onPressed: () => context.pop(),
        ),
        title: Text(
          '手机号注册',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
            color: const Color(0xFF333333),
          ),
        ),
        centerTitle: true,
      ),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: SafeArea(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 32.h),
                // 标题
                Text(
                  '输入手机号',
                  style: TextStyle(
                    fontSize: 24.sp,
                    fontWeight: FontWeight.w700,
                    color: const Color(0xFF333333),
                  ),
                ),
                SizedBox(height: 8.h),
                Text(
                  '我们将向您的手机发送验证码',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: const Color(0xFF999999),
                  ),
                ),
                SizedBox(height: 32.h),
                // 手机号输入框
                _buildPhoneInput(),
                // 错误信息
                if (_errorMessage != null) ...[
                  SizedBox(height: 8.h),
                  Text(
                    _errorMessage!,
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.red,
                    ),
                  ),
                ],
                const Spacer(),
                // 下一步按钮
                _buildNextButton(),
                SizedBox(height: 32.h),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildPhoneInput() {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFFF5F5F5),
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(
          color: _errorMessage != null
              ? Colors.red.withValues(alpha: 0.5)
              : Colors.transparent,
        ),
      ),
      child: Row(
        children: [
          // 国家/地区代码
          Container(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
            decoration: BoxDecoration(
              border: Border(
                right: BorderSide(
                  color: const Color(0xFFE0E0E0),
                  width: 1.w,
                ),
              ),
            ),
            child: Text(
              '+86',
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
                color: const Color(0xFF333333),
              ),
            ),
          ),
          // 手机号输入
          Expanded(
            child: TextField(
              controller: _phoneController,
              focusNode: _phoneFocusNode,
              keyboardType: TextInputType.phone,
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly,
                LengthLimitingTextInputFormatter(11),
              ],
              decoration: InputDecoration(
                hintText: '请输入手机号',
                hintStyle: TextStyle(
                  fontSize: 16.sp,
                  color: const Color(0xFFBBBBBB),
                ),
                border: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 16.w,
                  vertical: 16.h,
                ),
              ),
              style: TextStyle(
                fontSize: 16.sp,
                color: const Color(0xFF333333),
              ),
            ),
          ),
          // 清除按钮
          if (_phoneController.text.isNotEmpty)
            GestureDetector(
              onTap: () {
                _phoneController.clear();
                setState(() {});
              },
              child: Padding(
                padding: EdgeInsets.only(right: 16.w),
                child: Icon(
                  Icons.cancel,
                  size: 20.sp,
                  color: const Color(0xFFBBBBBB),
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildNextButton() {
    final isValid = _isValidPhoneNumber(_phoneController.text.trim());
    final canClick = isValid && !_isSending && _canSend;

    return GestureDetector(
      onTap: canClick ? _sendSmsCode : null,
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.symmetric(vertical: 16.h),
        decoration: BoxDecoration(
          color: canClick
              ? const Color(0xFF2E7D32)
              : const Color(0xFFE0E0E0),
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Center(
          child: _isSending
              ? SizedBox(
                  width: 24.sp,
                  height: 24.sp,
                  child: const CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                )
              : Text(
                  !_canSend ? '$_countdown秒后重新发送' : '获取验证码',
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                    color: canClick ? Colors.white : const Color(0xFF999999),
                  ),
                ),
        ),
      ),
    );
  }
}

/// 短信验证码页面参数
class SmsVerifyParams {
  final String phoneNumber;
  final SmsCodeType type;
  final String? inviterReferralCode;

  SmsVerifyParams({
    required this.phoneNumber,
    required this.type,
    this.inviterReferralCode,
  });
}
