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 '../../../../routes/route_paths.dart';
import 'kyc_entry_page.dart'; // 导入 kycServiceProvider

/// 更换手机号流程步骤
enum ChangePhoneStep {
  verifyOld,        // 验证旧手机
  verifySuccess,    // 验证成功，选择下一步操作（仅当首次验证时显示）
  inputNew,         // 输入新手机号
  verifyNew,        // 验证新手机
  success,          // 更换成功
}

/// 更换手机号页面
class ChangePhonePage extends ConsumerStatefulWidget {
  const ChangePhonePage({super.key});

  @override
  ConsumerState<ChangePhonePage> createState() => _ChangePhonePageState();
}

class _ChangePhonePageState extends ConsumerState<ChangePhonePage> {
  ChangePhoneStep _currentStep = ChangePhoneStep.verifyOld;

  // 旧手机验证
  final List<TextEditingController> _oldCodeControllers = List.generate(6, (_) => TextEditingController());
  final List<FocusNode> _oldCodeFocusNodes = List.generate(6, (_) => FocusNode());

  // 新手机号输入
  final _newPhoneController = TextEditingController();

  // 新手机验证
  final List<TextEditingController> _newCodeControllers = List.generate(6, (_) => TextEditingController());
  final List<FocusNode> _newCodeFocusNodes = List.generate(6, (_) => FocusNode());

  // 状态
  bool _isLoading = false;
  bool _isSendingCode = false;
  String? _errorMessage;
  String? _oldPhoneNumber;
  String? _changePhoneToken;

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

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

  @override
  void dispose() {
    _countdownTimer?.cancel();
    for (var c in _oldCodeControllers) {
      c.dispose();
    }
    for (var f in _oldCodeFocusNodes) {
      f.dispose();
    }
    _newPhoneController.dispose();
    for (var c in _newCodeControllers) {
      c.dispose();
    }
    for (var f in _newCodeFocusNodes) {
      f.dispose();
    }
    super.dispose();
  }

  Future<void> _loadPhoneStatus() async {
    try {
      final kycService = ref.read(kycServiceProvider);
      final status = await kycService.getPhoneStatus();
      if (mounted) {
        setState(() {
          _oldPhoneNumber = status.phoneNumber;
        });
      }
    } catch (e) {
      debugPrint('[ChangePhonePage] 加载手机号状态失败: $e');
    }
  }

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

  /// 发送旧手机验证码
  Future<void> _sendOldPhoneCode() async {
    if (_isSendingCode || _countdown > 0) return;

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

    try {
      final kycService = ref.read(kycServiceProvider);
      await kycService.sendOldPhoneCode();
      _startCountdown();
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('验证码已发送'), backgroundColor: Color(0xFF2E7D32)),
        );
      }
    } catch (e) {
      setState(() {
        _errorMessage = e.toString().replaceAll('Exception: ', '');
      });
    } finally {
      if (mounted) {
        setState(() => _isSendingCode = false);
      }
    }
  }

  /// 验证旧手机验证码
  Future<void> _verifyOldPhone() async {
    final code = _oldCodeControllers.map((c) => c.text).join();
    if (code.length != 6) {
      setState(() => _errorMessage = '请输入完整的验证码');
      return;
    }

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

    try {
      final kycService = ref.read(kycServiceProvider);
      final response = await kycService.verifyOldPhoneCode(code);

      setState(() {
        _changePhoneToken = response.changePhoneToken;
        _countdown = 0;
      });

      // 根据之前是否已验证决定跳转到哪个步骤
      if (mounted) {
        setState(() {
          if (!response.wasAlreadyVerified) {
            // 首次验证成功，显示选择页面
            _currentStep = ChangePhoneStep.verifySuccess;
          } else {
            // 之前已验证过，直接进入更换手机号流程
            _currentStep = ChangePhoneStep.inputNew;
          }
        });
      }
    } catch (e) {
      setState(() {
        _errorMessage = e.toString().replaceAll('Exception: ', '');
      });
      // 清空验证码
      for (var c in _oldCodeControllers) {
        c.clear();
      }
      _oldCodeFocusNodes[0].requestFocus();
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  /// 发送新手机验证码
  Future<void> _sendNewPhoneCode() async {
    final newPhone = _newPhoneController.text.trim();
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(newPhone)) {
      setState(() => _errorMessage = '请输入正确的手机号');
      return;
    }

    if (_isSendingCode || _countdown > 0) return;

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

    try {
      final kycService = ref.read(kycServiceProvider);
      await kycService.sendNewPhoneCode(
        newPhoneNumber: newPhone,
        changePhoneToken: _changePhoneToken!,
      );
      _startCountdown();
      setState(() {
        _currentStep = ChangePhoneStep.verifyNew;
      });
    } catch (e) {
      setState(() {
        _errorMessage = e.toString().replaceAll('Exception: ', '');
      });
    } finally {
      if (mounted) {
        setState(() => _isSendingCode = false);
      }
    }
  }

  /// 确认更换手机号
  Future<void> _confirmChangePhone() async {
    final code = _newCodeControllers.map((c) => c.text).join();
    if (code.length != 6) {
      setState(() => _errorMessage = '请输入完整的验证码');
      return;
    }

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

    try {
      final kycService = ref.read(kycServiceProvider);
      await kycService.confirmChangePhone(
        newPhoneNumber: _newPhoneController.text.trim(),
        smsCode: code,
        changePhoneToken: _changePhoneToken!,
      );

      setState(() {
        _currentStep = ChangePhoneStep.success;
      });
    } catch (e) {
      setState(() {
        _errorMessage = e.toString().replaceAll('Exception: ', '');
      });
      // 清空验证码
      for (var c in _newCodeControllers) {
        c.clear();
      }
      _newCodeFocusNodes[0].requestFocus();
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  void _onOldCodeChanged(int index, String value) {
    if (_errorMessage != null) {
      setState(() => _errorMessage = null);
    }
    if (value.isNotEmpty && index < 5) {
      _oldCodeFocusNodes[index + 1].requestFocus();
    } else if (value.isNotEmpty && index == 5) {
      _oldCodeFocusNodes[index].unfocus();
      _verifyOldPhone();
    }
  }

  void _onNewCodeChanged(int index, String value) {
    if (_errorMessage != null) {
      setState(() => _errorMessage = null);
    }
    if (value.isNotEmpty && index < 5) {
      _newCodeFocusNodes[index + 1].requestFocus();
    } else if (value.isNotEmpty && index == 5) {
      _newCodeFocusNodes[index].unfocus();
      _confirmChangePhone();
    }
  }

  @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: SafeArea(
        child: _buildContent(),
      ),
    );
  }

  Widget _buildContent() {
    switch (_currentStep) {
      case ChangePhoneStep.verifyOld:
        return _buildVerifyOldStep();
      case ChangePhoneStep.verifySuccess:
        return _buildVerifySuccessStep();
      case ChangePhoneStep.inputNew:
        return _buildInputNewStep();
      case ChangePhoneStep.verifyNew:
        return _buildVerifyNewStep();
      case ChangePhoneStep.success:
        return _buildSuccessStep();
    }
  }

  /// 步骤1: 验证旧手机
  Widget _buildVerifyOldStep() {
    return SingleChildScrollView(
      padding: EdgeInsets.symmetric(horizontal: 24.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 32.h),
          _buildStepIndicator(1),
          SizedBox(height: 24.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)),
          ),
          if (_oldPhoneNumber != null) ...[
            SizedBox(height: 8.h),
            Text(
              '当前手机号: $_oldPhoneNumber',
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
                color: const Color(0xFF2E7D32),
              ),
            ),
          ],
          SizedBox(height: 32.h),
          _buildCodeInputs(_oldCodeControllers, _oldCodeFocusNodes, _onOldCodeChanged),
          if (_errorMessage != null) ...[
            SizedBox(height: 16.h),
            Text(_errorMessage!, style: TextStyle(fontSize: 14.sp, color: Colors.red)),
          ],
          SizedBox(height: 24.h),
          _buildSendCodeButton(_sendOldPhoneCode),
          SizedBox(height: 40.h),
          _buildNextButton(
            onPressed: _isLoading ? null : _verifyOldPhone,
            text: '下一步',
            isLoading: _isLoading,
          ),
        ],
      ),
    );
  }

  /// 验证成功选择页面（首次验证手机号后显示）
  Widget _buildVerifySuccessStep() {
    return SingleChildScrollView(
      padding: EdgeInsets.symmetric(horizontal: 24.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(height: 60.h),
          // 成功图标
          Container(
            width: 80.w,
            height: 80.w,
            decoration: const BoxDecoration(
              color: Color(0xFFE8F5E9),
              shape: BoxShape.circle,
            ),
            child: Icon(
              Icons.check_circle,
              color: const Color(0xFF2E7D32),
              size: 50.sp,
            ),
          ),
          SizedBox(height: 24.h),
          Text(
            '恭喜您！',
            style: TextStyle(
              fontSize: 28.sp,
              fontWeight: FontWeight.w700,
              color: const Color(0xFF333333),
            ),
          ),
          SizedBox(height: 12.h),
          Text(
            '您的手机号已验证成功',
            style: TextStyle(
              fontSize: 16.sp,
              color: const Color(0xFF666666),
            ),
          ),
          if (_oldPhoneNumber != null) ...[
            SizedBox(height: 8.h),
            Text(
              _oldPhoneNumber!,
              style: TextStyle(
                fontSize: 20.sp,
                fontWeight: FontWeight.w600,
                color: const Color(0xFF2E7D32),
              ),
            ),
          ],
          SizedBox(height: 48.h),
          Text(
            '请选择下一步操作',
            style: TextStyle(
              fontSize: 14.sp,
              color: const Color(0xFF999999),
            ),
          ),
          SizedBox(height: 24.h),
          // 仅验证手机号按钮
          SizedBox(
            width: double.infinity,
            child: OutlinedButton(
              onPressed: () {
                // 刷新 KYC 状态后跳转到实名认证页面
                ref.invalidate(kycStatusProvider);
                context.go(RoutePaths.kycEntry);
              },
              style: OutlinedButton.styleFrom(
                padding: EdgeInsets.symmetric(vertical: 16.h),
                side: const BorderSide(color: Color(0xFF2E7D32), width: 1.5),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12.r),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.check, color: const Color(0xFF2E7D32), size: 20.sp),
                  SizedBox(width: 8.w),
                  Text(
                    '仅验证手机号，不更换',
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w600,
                      color: const Color(0xFF2E7D32),
                    ),
                  ),
                ],
              ),
            ),
          ),
          SizedBox(height: 16.h),
          // 继续更换手机号按钮
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: () {
                setState(() {
                  _currentStep = ChangePhoneStep.inputNew;
                });
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF2E7D32),
                padding: EdgeInsets.symmetric(vertical: 16.h),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12.r),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.swap_horiz, color: Colors.white, size: 20.sp),
                  SizedBox(width: 8.w),
                  Text(
                    '继续更换手机号',
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w600,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
            ),
          ),
          SizedBox(height: 32.h),
          // 提示文字
          Container(
            padding: EdgeInsets.all(16.w),
            decoration: BoxDecoration(
              color: const Color(0xFFF5F5F5),
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Row(
              children: [
                Icon(Icons.info_outline, color: const Color(0xFF999999), size: 18.sp),
                SizedBox(width: 8.w),
                Expanded(
                  child: Text(
                    '如需更换手机号，验证码将发送至新手机',
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: const Color(0xFF666666),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 步骤2: 输入新手机号
  Widget _buildInputNewStep() {
    return SingleChildScrollView(
      padding: EdgeInsets.symmetric(horizontal: 24.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 32.h),
          _buildStepIndicator(2),
          SizedBox(height: 24.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),
          TextFormField(
            controller: _newPhoneController,
            keyboardType: TextInputType.phone,
            maxLength: 11,
            inputFormatters: [FilteringTextInputFormatter.digitsOnly],
            decoration: InputDecoration(
              hintText: '请输入手机号',
              counterText: '',
              prefixIcon: const Icon(Icons.phone_android, color: Color(0xFF999999)),
              filled: true,
              fillColor: const Color(0xFFF5F5F5),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12.r),
                borderSide: BorderSide.none,
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12.r),
                borderSide: const BorderSide(color: Color(0xFF2E7D32), width: 2),
              ),
            ),
            style: TextStyle(fontSize: 16.sp, color: const Color(0xFF333333)),
          ),
          if (_errorMessage != null) ...[
            SizedBox(height: 16.h),
            Text(_errorMessage!, style: TextStyle(fontSize: 14.sp, color: Colors.red)),
          ],
          SizedBox(height: 40.h),
          _buildNextButton(
            onPressed: _isSendingCode ? null : _sendNewPhoneCode,
            text: '获取验证码',
            isLoading: _isSendingCode,
          ),
        ],
      ),
    );
  }

  /// 步骤3: 验证新手机
  Widget _buildVerifyNewStep() {
    return SingleChildScrollView(
      padding: EdgeInsets.symmetric(horizontal: 24.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 32.h),
          _buildStepIndicator(3),
          SizedBox(height: 24.h),
          Text(
            '验证新手机号',
            style: TextStyle(
              fontSize: 24.sp,
              fontWeight: FontWeight.w700,
              color: const Color(0xFF333333),
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            '验证码已发送至 ${_formatPhone(_newPhoneController.text)}',
            style: TextStyle(fontSize: 14.sp, color: const Color(0xFF999999)),
          ),
          SizedBox(height: 32.h),
          _buildCodeInputs(_newCodeControllers, _newCodeFocusNodes, _onNewCodeChanged),
          if (_errorMessage != null) ...[
            SizedBox(height: 16.h),
            Text(_errorMessage!, style: TextStyle(fontSize: 14.sp, color: Colors.red)),
          ],
          SizedBox(height: 24.h),
          _buildSendCodeButton(() async {
            final kycService = ref.read(kycServiceProvider);
            await kycService.sendNewPhoneCode(
              newPhoneNumber: _newPhoneController.text.trim(),
              changePhoneToken: _changePhoneToken!,
            );
            _startCountdown();
          }),
          SizedBox(height: 40.h),
          _buildNextButton(
            onPressed: _isLoading ? null : _confirmChangePhone,
            text: '确认更换',
            isLoading: _isLoading,
          ),
        ],
      ),
    );
  }

  /// 步骤4: 更换成功
  Widget _buildSuccessStep() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.check_circle, size: 80.sp, color: const Color(0xFF2E7D32)),
          SizedBox(height: 24.h),
          Text(
            '手机号更换成功',
            style: TextStyle(
              fontSize: 24.sp,
              fontWeight: FontWeight.w700,
              color: const Color(0xFF333333),
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            '新手机号: ${_formatPhone(_newPhoneController.text)}',
            style: TextStyle(fontSize: 16.sp, color: const Color(0xFF666666)),
          ),
          SizedBox(height: 40.h),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.w),
            child: _buildNextButton(
              onPressed: () => context.pop(),
              text: '完成',
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStepIndicator(int currentStep) {
    return Row(
      children: List.generate(3, (index) {
        final step = index + 1;
        final isActive = step <= currentStep;
        return Expanded(
          child: Row(
            children: [
              Container(
                width: 24.w,
                height: 24.w,
                decoration: BoxDecoration(
                  color: isActive ? const Color(0xFF2E7D32) : const Color(0xFFE0E0E0),
                  shape: BoxShape.circle,
                ),
                child: Center(
                  child: Text(
                    '$step',
                    style: TextStyle(
                      fontSize: 12.sp,
                      fontWeight: FontWeight.w600,
                      color: isActive ? Colors.white : const Color(0xFF999999),
                    ),
                  ),
                ),
              ),
              if (index < 2)
                Expanded(
                  child: Container(
                    height: 2,
                    color: step < currentStep ? const Color(0xFF2E7D32) : const Color(0xFFE0E0E0),
                  ),
                ),
            ],
          ),
        );
      }),
    );
  }

  Widget _buildCodeInputs(
    List<TextEditingController> controllers,
    List<FocusNode> focusNodes,
    void Function(int, String) onChanged,
  ) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: List.generate(6, (index) {
        return SizedBox(
          width: 48.w,
          height: 56.h,
          child: TextField(
            controller: controllers[index],
            focusNode: focusNodes[index],
            keyboardType: TextInputType.number,
            textAlign: TextAlign.center,
            maxLength: 1,
            inputFormatters: [FilteringTextInputFormatter.digitsOnly],
            decoration: InputDecoration(
              counterText: '',
              filled: true,
              fillColor: const Color(0xFFF5F5F5),
              contentPadding: EdgeInsets.zero,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12.r),
                borderSide: BorderSide.none,
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12.r),
                borderSide: const BorderSide(color: Color(0xFF2E7D32), width: 2),
              ),
            ),
            style: TextStyle(
              fontSize: 24.sp,
              fontWeight: FontWeight.w700,
              color: const Color(0xFF333333),
            ),
            onChanged: (value) => onChanged(index, value),
          ),
        );
      }),
    );
  }

  Widget _buildSendCodeButton(Future<void> Function() onSend) {
    final canSend = _countdown == 0 && !_isSendingCode;
    return Center(
      child: GestureDetector(
        onTap: canSend ? () async {
          try {
            await onSend();
          } catch (e) {
            if (mounted) {
              setState(() {
                _errorMessage = e.toString().replaceAll('Exception: ', '');
              });
            }
          }
        } : null,
        child: _isSendingCode
            ? SizedBox(
                width: 20.sp,
                height: 20.sp,
                child: const CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF999999)),
                ),
              )
            : Text(
                _countdown > 0 ? '$_countdown秒后重新发送' : '发送验证码',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  color: canSend ? const Color(0xFF2E7D32) : const Color(0xFF999999),
                ),
              ),
      ),
    );
  }

  Widget _buildNextButton({
    required VoidCallback? onPressed,
    required String text,
    bool isLoading = false,
  }) {
    return GestureDetector(
      onTap: onPressed,
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.symmetric(vertical: 16.h),
        decoration: BoxDecoration(
          color: onPressed == null ? const Color(0xFFCCCCCC) : const Color(0xFF2E7D32),
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: isLoading
            ? Center(
                child: SizedBox(
                  width: 24.sp,
                  height: 24.sp,
                  child: const CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                ),
              )
            : Text(
                text,
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w600,
                  color: Colors.white,
                ),
                textAlign: TextAlign.center,
              ),
      ),
    );
  }

  String _formatPhone(String phone) {
    if (phone.length != 11) return phone;
    return '${phone.substring(0, 3)} **** ${phone.substring(7)}';
  }
}
