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';

/// 修改密码页面
/// 支持设置或修改登录密码
class ChangePasswordPage extends ConsumerStatefulWidget {
  const ChangePasswordPage({super.key});

  @override
  ConsumerState<ChangePasswordPage> createState() => _ChangePasswordPageState();
}

class _ChangePasswordPageState extends ConsumerState<ChangePasswordPage> {
  /// 旧密码控制器
  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 _hasPassword = false;

  /// 是否正在加载
  bool _isLoading = true;

  /// 加载状态是否出错
  bool _isLoadError = false;

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

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

  /// 加载密码状态
  Future<void> _loadPasswordStatus() async {
    setState(() {
      _isLoading = true;
      _isLoadError = false;
    });

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

      if (mounted) {
        setState(() {
          _hasPassword = hasPassword;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoadError = true;
          _isLoading = false;
        });
      }
    }
  }

  /// 返回上一页
  void _goBack() {
    context.pop();
  }

  /// 验证密码强度
  String? _validatePasswordStrength(String password) {
    if (password.length < 8) {
      return '密码长度至少8位';
    }
    if (password.length > 20) {
      return '密码长度不能超过20位';
    }
    if (!RegExp(r'[A-Za-z]').hasMatch(password)) {
      return '密码必须包含字母';
    }
    if (!RegExp(r'[0-9]').hasMatch(password)) {
      return '密码必须包含数字';
    }
    return null;
  }

  /// 提交修改密码
  Future<void> _submitPassword() async {
    final oldPassword = _oldPasswordController.text;
    final newPassword = _newPasswordController.text;
    final confirmPassword = _confirmPasswordController.text;

    // 验证旧密码（如果已设置过密码）
    if (_hasPassword && oldPassword.isEmpty) {
      _showErrorSnackBar('请输入当前密码');
      return;
    }

    // 验证新密码
    if (newPassword.isEmpty) {
      _showErrorSnackBar('请输入新密码');
      return;
    }

    final strengthError = _validatePasswordStrength(newPassword);
    if (strengthError != null) {
      _showErrorSnackBar(strengthError);
      return;
    }

    // 验证确认密码
    if (confirmPassword.isEmpty) {
      _showErrorSnackBar('请确认新密码');
      return;
    }

    if (newPassword != confirmPassword) {
      _showErrorSnackBar('两次输入的密码不一致');
      return;
    }

    setState(() {
      _isSubmitting = true;
    });

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

      if (_hasPassword) {
        // 已有密码，调用修改密码 API
        await accountService.changePassword(
          oldPassword: oldPassword,
          newPassword: newPassword,
        );
      } else {
        // 未设置过密码，调用设置密码 API
        await accountService.setLoginPassword(newPassword);
      }

      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(_hasPassword ? '密码修改成功' : '密码设置成功'),
            backgroundColor: const Color(0xFF4CAF50),
          ),
        );

        context.pop(true);
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });

        _showErrorSnackBar('操作失败: ${e.toString().replaceAll('Exception: ', '')}');
      }
    }
  }

  /// 显示错误提示
  void _showErrorSnackBar(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: _loadPasswordStatus,
                                  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 (_hasPassword) ...[
                              _buildPasswordInput(
                                controller: _oldPasswordController,
                                label: '当前密码',
                                hint: '请输入当前密码',
                                showPassword: _showOldPassword,
                                onToggleVisibility: () {
                                  setState(() {
                                    _showOldPassword = !_showOldPassword;
                                  });
                                },
                              ),
                              const SizedBox(height: 16),
                            ],

                            // 新密码输入
                            _buildPasswordInput(
                              controller: _newPasswordController,
                              label: '新密码',
                              hint: '请输入新密码',
                              showPassword: _showNewPassword,
                              onToggleVisibility: () {
                                setState(() {
                                  _showNewPassword = !_showNewPassword;
                                });
                              },
                            ),
                            const SizedBox(height: 16),

                            // 确认密码输入
                            _buildPasswordInput(
                              controller: _confirmPasswordController,
                              label: '确认密码',
                              hint: '请再次输入新密码',
                              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: _goBack,
            child: Container(
              width: 48,
              height: 48,
              alignment: Alignment.center,
              child: const Icon(
                Icons.arrow_back,
                size: 24,
                color: Color(0xFF5D4037),
              ),
            ),
          ),
          // 标题
          Expanded(
            child: Text(
              _hasPassword ? '修改密码' : '设置密码',
              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: _hasPassword
                  ? const Color(0xFF4CAF50).withValues(alpha: 0.1)
                  : const Color(0xFFFF9800).withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(24),
            ),
            child: Icon(
              _hasPassword ? Icons.lock : Icons.lock_open,
              color: _hasPassword ? const Color(0xFF4CAF50) : const Color(0xFFFF9800),
              size: 24,
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _hasPassword ? '已设置密码' : '未设置密码',
                  style: TextStyle(
                    fontSize: 18,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w600,
                    color: _hasPassword ? const Color(0xFF4CAF50) : const Color(0xFFFF9800),
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  _hasPassword ? '您可以修改当前登录密码' : '设置密码后可使用密码登录',
                  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: [
          Row(
            children: const [
              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('长度为 8-20 个字符'),
          _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),
          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,
            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,
              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 : _submitPassword,
      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(
                  _hasPassword ? '修改密码' : '设置密码',
                  style: const TextStyle(
                    fontSize: 16,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w700,
                    height: 1.5,
                    letterSpacing: 0.24,
                    color: Colors.white,
                  ),
                ),
        ),
      ),
    );
  }
}
