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

/// 支付密码设置/修改页面
///
/// - 未设置时：直接输入新密码（首次设置）
/// - 已设置时：需验证旧密码后修改
///
/// 支付密码格式：6位纯数字
class ChangePaymentPasswordPage extends ConsumerStatefulWidget {
  const ChangePaymentPasswordPage({super.key});

  @override
  ConsumerState<ChangePaymentPasswordPage> createState() =>
      _ChangePaymentPasswordPageState();
}

class _ChangePaymentPasswordPageState
    extends ConsumerState<ChangePaymentPasswordPage> {
  final TextEditingController _oldPasswordController = TextEditingController();
  final TextEditingController _newPasswordController = TextEditingController();
  final TextEditingController _confirmPasswordController =
      TextEditingController();

  bool _showOldPassword = false;
  bool _showNewPassword = false;
  bool _showConfirmPassword = false;
  bool _isSubmitting = false;
  bool _hasPaymentPassword = false;
  bool _isLoading = true;
  bool _isLoadError = false;

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

  @override
  void dispose() {
    _oldPasswordController.dispose();
    _newPasswordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  Future<void> _loadStatus() async {
    setState(() => _isLoading = true);
    try {
      final accountService = ref.read(accountServiceProvider);
      final hasPassword = await accountService.isPaymentPasswordSet();
      if (mounted) {
        setState(() {
          _hasPaymentPassword = hasPassword;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoadError = true;
          _isLoading = false;
        });
      }
    }
  }

  /// 校验支付密码格式：6位纯数字
  String? _validatePassword(String password) {
    if (password.length != 6) return '支付密码必须为6位数字';
    if (!RegExp(r'^\d{6}$').hasMatch(password)) return '支付密码只能包含数字';
    return null;
  }

  Future<void> _submit() async {
    final oldPassword = _oldPasswordController.text;
    final newPassword = _newPasswordController.text;
    final confirmPassword = _confirmPasswordController.text;

    if (_hasPaymentPassword && oldPassword.isEmpty) {
      _showError('请输入当前支付密码');
      return;
    }
    if (newPassword.isEmpty) {
      _showError('请输入新支付密码');
      return;
    }
    final formatError = _validatePassword(newPassword);
    if (formatError != null) {
      _showError(formatError);
      return;
    }
    if (confirmPassword != newPassword) {
      _showError('两次输入的支付密码不一致');
      return;
    }

    setState(() => _isSubmitting = true);
    try {
      final accountService = ref.read(accountServiceProvider);
      if (_hasPaymentPassword) {
        await accountService.changePaymentPassword(
          oldPassword: oldPassword,
          newPassword: newPassword,
        );
      } else {
        await accountService.setPaymentPassword(newPassword);
      }

      if (mounted) {
        setState(() => _isSubmitting = false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(_hasPaymentPassword ? '支付密码修改成功' : '支付密码设置成功'),
            backgroundColor: const Color(0xFF4CAF50),
          ),
        );
        context.pop(true);
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isSubmitting = false);
        _showError(
            '操作失败: ${e.toString().replaceAll('Exception: ', '')}');
      }
    }
  }

  void _showError(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: Colors.red),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFFFFF5E6), Color(0xFFFFE4B5)],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              _buildAppBar(),
              Expanded(
                child: _isLoading
                    ? const Center(
                        child: CircularProgressIndicator(
                          valueColor: AlwaysStoppedAnimation<Color>(
                              Color(0xFFD4AF37)),
                        ),
                      )
                    : _isLoadError
                        ? Center(
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                const Icon(Icons.error_outline, color: Colors.red, size: 48),
                                const SizedBox(height: 12),
                                const Text('加载失败，请重试', style: TextStyle(color: Colors.red)),
                                const SizedBox(height: 16),
                                ElevatedButton(
                                  onPressed: _loadStatus,
                                  style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFFD4AF37)),
                                  child: const Text('重试', style: TextStyle(color: Colors.white)),
                                ),
                              ],
                            ),
                          )
                        : SingleChildScrollView(
                        padding: const EdgeInsets.all(16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            _buildStatusCard(),
                            const SizedBox(height: 24),
                            _buildPasswordRequirements(),
                            const SizedBox(height: 24),
                            if (_hasPaymentPassword) ...[
                              _buildPasswordInput(
                                controller: _oldPasswordController,
                                label: '当前支付密码',
                                hint: '请输入当前6位支付密码',
                                showPassword: _showOldPassword,
                                onToggleVisibility: () => setState(
                                    () => _showOldPassword = !_showOldPassword),
                              ),
                              // 忘记支付密码入口 [2026-03-05]
                              Align(
                                alignment: Alignment.centerRight,
                                child: GestureDetector(
                                  onTap: () => context.push(
                                    RoutePaths.resetPaymentPassword,
                                  ),
                                  child: const Padding(
                                    padding: EdgeInsets.only(top: 8),
                                    child: Text(
                                      '忘记支付密码？',
                                      style: TextStyle(
                                        fontSize: 13,
                                        color: Color(0xFFD4AF37),
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                              const SizedBox(height: 8),
                            ],
                            _buildPasswordInput(
                              controller: _newPasswordController,
                              label: '新支付密码',
                              hint: '请输入6位数字支付密码',
                              showPassword: _showNewPassword,
                              onToggleVisibility: () => setState(
                                  () => _showNewPassword = !_showNewPassword),
                            ),
                            const SizedBox(height: 16),
                            _buildPasswordInput(
                              controller: _confirmPasswordController,
                              label: '确认支付密码',
                              hint: '请再次输入6位支付密码',
                              showPassword: _showConfirmPassword,
                              onToggleVisibility: () => setState(() =>
                                  _showConfirmPassword = !_showConfirmPassword),
                            ),
                            const SizedBox(height: 32),
                            _buildSubmitButton(),
                          ],
                        ),
                      ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildAppBar() {
    return Container(
      height: 64,
      padding: const EdgeInsets.only(top: 16, left: 16, right: 16),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => context.pop(),
            child: Container(
              width: 48,
              height: 48,
              alignment: Alignment.center,
              child: const Icon(Icons.arrow_back,
                  size: 24, color: Color(0xFF5D4037)),
            ),
          ),
          Expanded(
            child: Text(
              _hasPaymentPassword ? '修改支付密码' : '设置支付密码',
              style: const TextStyle(
                fontSize: 18,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w500,
                height: 1.25,
                letterSpacing: -0.27,
                color: Color(0xFF5D4037),
              ),
              textAlign: TextAlign.center,
            ),
          ),
          const SizedBox(width: 48),
        ],
      ),
    );
  }

  Widget _buildStatusCard() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0x80FFFFFF),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: const Color(0x33D4AF37), width: 1),
      ),
      child: Row(
        children: [
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: _hasPaymentPassword
                  ? const Color(0xFF4CAF50).withValues(alpha: 0.1)
                  : const Color(0xFFFF9800).withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(24),
            ),
            child: Icon(
              _hasPaymentPassword ? Icons.payment : Icons.payment_outlined,
              color: _hasPaymentPassword
                  ? const Color(0xFF4CAF50)
                  : const Color(0xFFFF9800),
              size: 24,
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _hasPaymentPassword ? '已设置支付密码' : '未设置支付密码',
                  style: TextStyle(
                    fontSize: 18,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w600,
                    color: _hasPaymentPassword
                        ? const Color(0xFF4CAF50)
                        : const Color(0xFFFF9800),
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  _hasPaymentPassword
                      ? '认种、预种等支付操作需要验证支付密码'
                      : '设置后，认种和预种时需输入支付密码确认',
                  style: const TextStyle(
                    fontSize: 14,
                    fontFamily: 'Inter',
                    color: Color(0xFF745D43),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPasswordRequirements() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFFFFF5E6),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: const Color(0x33D4AF37), width: 1),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Row(
            children: [
              Icon(Icons.info_outline, size: 20, color: Color(0xFF8B5A2B)),
              SizedBox(width: 8),
              Text(
                '支付密码要求',
                style: TextStyle(
                  fontSize: 16,
                  fontFamily: 'Inter',
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF5D4037),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          _buildRequirementItem('必须为 6 位纯数字'),
          _buildRequirementItem('与登录密码相互独立'),
          _buildRequirementItem('用于认种、预种等支付场景的二次验证'),
        ],
      ),
    );
  }

  Widget _buildRequirementItem(String text) {
    return Padding(
      padding: const EdgeInsets.only(top: 8),
      child: Row(
        children: [
          const Icon(Icons.check_circle_outline,
              size: 16, color: Color(0xFFD4AF37)),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              text,
              style: const TextStyle(
                fontSize: 14,
                fontFamily: 'Inter',
                color: Color(0xFF745D43),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPasswordInput({
    required TextEditingController controller,
    required String label,
    required String hint,
    required bool showPassword,
    required VoidCallback onToggleVisibility,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 16,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w500,
            color: Color(0xFF5D4037),
          ),
        ),
        const SizedBox(height: 8),
        Container(
          width: double.infinity,
          height: 54,
          decoration: BoxDecoration(
            color: const Color(0x80FFFFFF),
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: const Color(0x80FFFFFF), width: 1),
            boxShadow: const [
              BoxShadow(
                color: Color(0x0D000000),
                blurRadius: 2,
                offset: Offset(0, 1),
              ),
            ],
          ),
          child: TextField(
            controller: controller,
            obscureText: !showPassword,
            keyboardType: TextInputType.number,
            maxLength: 6,
            style: const TextStyle(
              fontSize: 16,
              fontFamily: 'Inter',
              height: 1.19,
              color: Color(0xFF5D4037),
            ),
            decoration: InputDecoration(
              contentPadding:
                  const EdgeInsets.symmetric(horizontal: 16, vertical: 15),
              border: InputBorder.none,
              counterText: '',
              hintText: hint,
              hintStyle: const TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                height: 1.19,
                color: Color(0x995D4037),
              ),
              suffixIcon: GestureDetector(
                onTap: onToggleVisibility,
                child: Icon(
                  showPassword ? Icons.visibility_off : Icons.visibility,
                  color: const Color(0xFF8B5A2B),
                  size: 20,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildSubmitButton() {
    return GestureDetector(
      onTap: _isSubmitting ? null : _submit,
      child: Container(
        width: double.infinity,
        height: 56,
        decoration: BoxDecoration(
          color: _isSubmitting
              ? const Color(0xFFD4AF37).withValues(alpha: 0.5)
              : const Color(0xFFD4AF37),
          borderRadius: BorderRadius.circular(12),
          boxShadow: const [
            BoxShadow(
              color: Color(0x4DD4AF37),
              blurRadius: 14,
              offset: Offset(0, 4),
            ),
          ],
        ),
        child: Center(
          child: _isSubmitting
              ? const SizedBox(
                  width: 24,
                  height: 24,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                )
              : Text(
                  _hasPaymentPassword ? '修改支付密码' : '设置支付密码',
                  style: const TextStyle(
                    fontSize: 16,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w700,
                    height: 1.5,
                    letterSpacing: 0.24,
                    color: Colors.white,
                  ),
                ),
        ),
      ),
    );
  }
}
