import 'package:flutter/material.dart';

/// 认种密码验证回调类型
///
/// [password] 用户输入的密码明文
/// 返回 true 表示密码正确，false 表示密码错误（如 valid=false），
/// 抛出异常表示网络/系统错误（由弹窗捕获并展示提示）
typedef PasswordVerifyCallback = Future<bool> Function(String password);

/// 密码校验弹窗（通用）
///
/// 支持两种模式：
/// - 登录密码验证（认种/预种前身份核实）
/// - 支付密码验证（认种/预种支付二次确认）
///
/// 调用方式：
/// ```dart
/// // 验证支付密码
/// final verified = await PasswordVerifyDialog.show(
///   context: context,
///   title: '验证支付密码',
///   subtitle: '请输入6位支付密码以确认认种',
///   hint: '请输入支付密码',
///   onVerify: (password) => accountService.verifyPaymentPassword(password),
/// );
/// if (verified == true) _submitPlanting();
/// ```
///
/// 后端接口：POST /user/verify-payment-password → { valid: bool }
class PasswordVerifyDialog extends StatefulWidget {
  /// 密码校验回调，由调用方注入
  final PasswordVerifyCallback onVerify;

  /// 弹窗标题，默认"验证登录密码"
  final String title;

  /// 说明文字，默认"为保障账户安全，请输入您的登录密码以继续"
  final String subtitle;

  /// 输入框 hint，默认"请输入登录密码"
  final String hint;

  const PasswordVerifyDialog({
    super.key,
    required this.onVerify,
    this.title = '验证登录密码',
    this.subtitle = '为保障账户安全，请输入您的登录密码以继续',
    this.hint = '请输入登录密码',
  });

  /// 显示密码验证弹窗
  /// 返回 true 表示验证通过，false/null 表示用户取消
  static Future<bool?> show({
    required BuildContext context,
    required PasswordVerifyCallback onVerify,
    String title = '验证登录密码',
    String subtitle = '为保障账户安全，请输入您的登录密码以继续',
    String hint = '请输入登录密码',
  }) {
    return showDialog<bool>(
      context: context,
      barrierDismissible: false,
      barrierColor: const Color(0x80000000),
      builder: (context) => PasswordVerifyDialog(
        onVerify: onVerify,
        title: title,
        subtitle: subtitle,
        hint: hint,
      ),
    );
  }

  @override
  State<PasswordVerifyDialog> createState() => _PasswordVerifyDialogState();
}

class _PasswordVerifyDialogState extends State<PasswordVerifyDialog> {
  final TextEditingController _passwordController = TextEditingController();

  bool _showPassword = false;
  bool _isVerifying = false;
  String? _errorMessage;

  @override
  void dispose() {
    _passwordController.dispose();
    super.dispose();
  }

  /// 点击确认按钮
  ///
  /// 流程：
  /// 1. 校验输入不为空
  /// 2. 调用 [onVerify] 发起网络请求
  /// 3. valid=true → 关闭弹窗并返回 true（调用方继续提交）
  /// 4. valid=false → 展示"密码错误"提示，留在弹窗
  /// 5. 抛出"尚未设置支付密码"异常 → 引导用户先完成设置
  /// 6. 其他异常（网络错误等）→ 展示系统错误提示，留在弹窗
  Future<void> _handleConfirm() async {
    final password = _passwordController.text.trim();
    if (password.isEmpty) {
      setState(() => _errorMessage = widget.hint);
      return;
    }

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

    try {
      final success = await widget.onVerify(password);
      if (!mounted) return;
      if (success) {
        // 密码正确：关闭弹窗，返回 true 通知调用方继续提交
        Navigator.pop(context, true);
      } else {
        // 密码错误（valid=false）：提示用户重试
        setState(() {
          _isVerifying = false;
          _errorMessage = '密码错误，请重试';
        });
      }
    } catch (e) {
      if (!mounted) return;
      final msg = e.toString();
      // 未设置支付密码：给出明确引导，而非误导性的"网络错误"
      final isNotSet = msg.contains('尚未设置支付密码') || msg.contains('payment password not set');
      setState(() {
        _isVerifying = false;
        _errorMessage = isNotSet
            ? '请先前往「我的」→「支付密码」完成设置'
            : '验证失败，请检查网络后重试';
      });
    }
  }

  /// 关闭弹窗
  void _handleClose() {
    Navigator.pop(context, false);
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: Colors.transparent,
      insetPadding: const EdgeInsets.symmetric(horizontal: 16),
      child: Container(
        width: double.infinity,
        constraints: const BoxConstraints(maxWidth: 384),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: const [
            BoxShadow(
              color: Color(0x40000000),
              blurRadius: 50,
              offset: Offset(0, 25),
              spreadRadius: -12,
            ),
          ],
        ),
        child: Stack(
          children: [
            // 主内容
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 32),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  _buildIcon(),
                  const SizedBox(height: 4),
                  _buildTitle(),
                  const SizedBox(height: 8),
                  _buildSubtitle(),
                  const SizedBox(height: 20),
                  _buildPasswordInput(),
                  if (_errorMessage != null) ...[
                    const SizedBox(height: 8),
                    _buildErrorMessage(),
                  ],
                  const SizedBox(height: 20),
                  _buildConfirmButton(),
                ],
              ),
            ),
            // 右上角关闭按钮
            Positioned(
              top: 8,
              right: 8,
              child: GestureDetector(
                onTap: _isVerifying ? null : _handleClose,
                child: Container(
                  width: 32,
                  height: 32,
                  decoration: BoxDecoration(
                    color: const Color(0x0D000000),
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: const Icon(
                    Icons.close,
                    size: 18,
                    color: Color(0xFF8B5A2B),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建锁图标
  Widget _buildIcon() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 16),
      child: Container(
        width: 60,
        height: 60,
        decoration: BoxDecoration(
          color: const Color(0xFFFFF7E6),
          borderRadius: BorderRadius.circular(30),
        ),
        child: const Center(
          child: Icon(
            Icons.lock_outline,
            color: Color(0xFF8B5A2B),
            size: 32,
          ),
        ),
      ),
    );
  }

  /// 构建标题
  Widget _buildTitle() {
    return Text(
      widget.title,
      style: const TextStyle(
        fontSize: 20,
        fontFamily: 'Inter',
        fontWeight: FontWeight.w700,
        height: 1.3,
        letterSpacing: -0.3,
        color: Color(0xFF5D4037),
      ),
      textAlign: TextAlign.center,
    );
  }

  /// 构建说明文字
  Widget _buildSubtitle() {
    return Text(
      widget.subtitle,
      style: const TextStyle(
        fontSize: 14,
        fontFamily: 'Inter',
        height: 1.5,
        color: Color(0xFF745D43),
      ),
      textAlign: TextAlign.center,
    );
  }

  /// 构建密码输入框
  Widget _buildPasswordInput() {
    final hasError = _errorMessage != null;
    return Container(
      width: double.infinity,
      height: 52,
      decoration: BoxDecoration(
        color: const Color(0xFFFFF7E6),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: hasError
              ? const Color(0xFFFF4D4F)
              : const Color(0x4D8B5A2B),
          width: 1,
        ),
      ),
      child: TextField(
        controller: _passwordController,
        obscureText: !_showPassword,
        enabled: !_isVerifying,
        onChanged: (_) {
          if (_errorMessage != null) {
            setState(() => _errorMessage = null);
          }
        },
        style: const TextStyle(
          fontSize: 16,
          fontFamily: 'Inter',
          height: 1.19,
          color: Color(0xFF5D4037),
        ),
        decoration: InputDecoration(
          contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
          border: InputBorder.none,
          hintText: widget.hint,
          hintStyle: const TextStyle(
            fontSize: 16,
            fontFamily: 'Inter',
            height: 1.19,
            color: Color(0x995D4037),
          ),
          suffixIcon: GestureDetector(
            onTap: () => setState(() => _showPassword = !_showPassword),
            child: Icon(
              _showPassword ? Icons.visibility_off : Icons.visibility,
              color: const Color(0xFF8B5A2B),
              size: 20,
            ),
          ),
        ),
      ),
    );
  }

  /// 构建错误提示
  Widget _buildErrorMessage() {
    return Align(
      alignment: Alignment.centerLeft,
      child: Row(
        children: [
          const Icon(
            Icons.error_outline,
            size: 14,
            color: Color(0xFFFF4D4F),
          ),
          const SizedBox(width: 4),
          Text(
            _errorMessage!,
            style: const TextStyle(
              fontSize: 12,
              fontFamily: 'Inter',
              color: Color(0xFFFF4D4F),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建确认按钮
  Widget _buildConfirmButton() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: SizedBox(
        width: double.infinity,
        child: GestureDetector(
          onTap: _isVerifying ? null : _handleConfirm,
          child: Container(
            height: 48,
            decoration: BoxDecoration(
              color: _isVerifying
                  ? const Color(0xFFD4AF37).withValues(alpha: 0.5)
                  : const Color(0xFFD4AF37),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Center(
              child: _isVerifying
                  ? const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    )
                  : const Text(
                      '确认',
                      style: TextStyle(
                        fontSize: 16,
                        fontFamily: 'Inter',
                        fontWeight: FontWeight.w700,
                        height: 1.5,
                        letterSpacing: 0.24,
                        color: Colors.white,
                      ),
                    ),
            ),
          ),
        ),
      ),
    );
  }
}
