import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/constants/app_colors.dart';
import '../../providers/user_providers.dart';

/// 支付密码设置/修改页面
class TradePasswordPage extends ConsumerStatefulWidget {
  const TradePasswordPage({super.key});

  @override
  ConsumerState<TradePasswordPage> createState() => _TradePasswordPageState();
}

class _TradePasswordPageState extends ConsumerState<TradePasswordPage> {
  final _formKey = GlobalKey<FormState>();
  final _loginPasswordController = TextEditingController();
  final _tradePasswordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();
  final _oldTradePasswordController = TextEditingController();

  bool _obscureLoginPassword = true;
  bool _obscureTradePassword = true;
  bool _obscureConfirmPassword = true;
  bool _obscureOldTradePassword = true;
  bool _hasTradePassword = false;
  bool _isLoadingStatus = true;

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

  Future<void> _loadTradePasswordStatus() async {
    final status = await ref.read(userNotifierProvider.notifier).getTradePasswordStatus();
    if (mounted) {
      setState(() {
        _hasTradePassword = status;
        _isLoadingStatus = false;
      });
    }
  }

  @override
  void dispose() {
    _loginPasswordController.dispose();
    _tradePasswordController.dispose();
    _confirmPasswordController.dispose();
    _oldTradePasswordController.dispose();
    super.dispose();
  }

  Future<void> _submit() async {
    if (!_formKey.currentState!.validate()) return;

    try {
      if (_hasTradePassword) {
        // 修改支付密码
        await ref.read(userNotifierProvider.notifier).changeTradePassword(
          _oldTradePasswordController.text,
          _tradePasswordController.text,
        );
      } else {
        // 设置支付密码
        await ref.read(userNotifierProvider.notifier).setTradePassword(
          _loginPasswordController.text,
          _tradePasswordController.text,
        );
      }

      if (mounted) {
        // 刷新支付密码状态
        ref.invalidate(tradePasswordStatusProvider);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(_hasTradePassword ? '支付密码修改成功' : '支付密码设置成功'),
            backgroundColor: AppColors.up,
          ),
        );
        context.pop();
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('操作失败: $e'),
            backgroundColor: AppColors.error,
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final userState = ref.watch(userNotifierProvider);

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.black),
          onPressed: () => context.pop(),
        ),
        title: Text(
          _hasTradePassword ? '修改支付密码' : '设置支付密码',
          style: const TextStyle(color: Colors.black),
        ),
        centerTitle: true,
      ),
      body: _isLoadingStatus
          ? const Center(child: CircularProgressIndicator())
          : SafeArea(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(24),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      const SizedBox(height: 16),

                      // 说明文字
                      Container(
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: AppColors.primary.withValues(alpha: 0.1),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Row(
                          children: [
                            Icon(Icons.info_outline, color: AppColors.primary, size: 24),
                            const SizedBox(width: 12),
                            Expanded(
                              child: Text(
                                '支付密码用于交易时的安全验证，请设置6位数字密码',
                                style: TextStyle(
                                  fontSize: 14,
                                  color: AppColors.primary,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),

                      const SizedBox(height: 24),

                      if (_hasTradePassword) ...[
                        // 旧支付密码（修改时需要）
                        TextFormField(
                          controller: _oldTradePasswordController,
                          obscureText: _obscureOldTradePassword,
                          keyboardType: TextInputType.number,
                          inputFormatters: [
                            FilteringTextInputFormatter.digitsOnly,
                            LengthLimitingTextInputFormatter(6),
                          ],
                          decoration: InputDecoration(
                            labelText: '原支付密码',
                            prefixIcon: const Icon(Icons.lock_outline),
                            suffixIcon: IconButton(
                              icon: Icon(
                                _obscureOldTradePassword ? Icons.visibility_off : Icons.visibility,
                              ),
                              onPressed: () => setState(() => _obscureOldTradePassword = !_obscureOldTradePassword),
                            ),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                          ),
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return '请输入原支付密码';
                            }
                            if (value.length != 6) {
                              return '支付密码必须是6位数字';
                            }
                            return null;
                          },
                        ),
                        const SizedBox(height: 16),
                      ] else ...[
                        // 登录密码验证（首次设置时需要）
                        TextFormField(
                          controller: _loginPasswordController,
                          obscureText: _obscureLoginPassword,
                          decoration: InputDecoration(
                            labelText: '登录密码',
                            hintText: '请输入登录密码以验证身份',
                            prefixIcon: const Icon(Icons.lock),
                            suffixIcon: IconButton(
                              icon: Icon(
                                _obscureLoginPassword ? Icons.visibility_off : Icons.visibility,
                              ),
                              onPressed: () => setState(() => _obscureLoginPassword = !_obscureLoginPassword),
                            ),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                          ),
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return '请输入登录密码';
                            }
                            return null;
                          },
                        ),
                        const SizedBox(height: 16),
                      ],

                      // 新支付密码
                      TextFormField(
                        controller: _tradePasswordController,
                        obscureText: _obscureTradePassword,
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                          LengthLimitingTextInputFormatter(6),
                        ],
                        decoration: InputDecoration(
                          labelText: _hasTradePassword ? '新支付密码' : '支付密码',
                          hintText: '请输入6位数字',
                          prefixIcon: const Icon(Icons.security),
                          suffixIcon: IconButton(
                            icon: Icon(
                              _obscureTradePassword ? Icons.visibility_off : Icons.visibility,
                            ),
                            onPressed: () => setState(() => _obscureTradePassword = !_obscureTradePassword),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return '请输入支付密码';
                          }
                          if (value.length != 6) {
                            return '支付密码必须是6位数字';
                          }
                          if (_hasTradePassword && value == _oldTradePasswordController.text) {
                            return '新密码不能与原密码相同';
                          }
                          return null;
                        },
                      ),

                      const SizedBox(height: 16),

                      // 确认支付密码
                      TextFormField(
                        controller: _confirmPasswordController,
                        obscureText: _obscureConfirmPassword,
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                          LengthLimitingTextInputFormatter(6),
                        ],
                        decoration: InputDecoration(
                          labelText: '确认支付密码',
                          hintText: '请再次输入6位数字',
                          prefixIcon: const Icon(Icons.security),
                          suffixIcon: IconButton(
                            icon: Icon(
                              _obscureConfirmPassword ? Icons.visibility_off : Icons.visibility,
                            ),
                            onPressed: () => setState(() => _obscureConfirmPassword = !_obscureConfirmPassword),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return '请确认支付密码';
                          }
                          if (value != _tradePasswordController.text) {
                            return '两次密码输入不一致';
                          }
                          return null;
                        },
                      ),

                      const SizedBox(height: 32),

                      // 提交按钮
                      SizedBox(
                        height: 52,
                        child: ElevatedButton(
                          onPressed: userState.isLoading ? null : _submit,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: AppColors.primary,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                          ),
                          child: userState.isLoading
                              ? const SizedBox(
                                  width: 24,
                                  height: 24,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                    color: Colors.white,
                                  ),
                                )
                              : Text(
                                  _hasTradePassword ? '确认修改' : '确认设置',
                                  style: const TextStyle(
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                    color: Colors.white,
                                  ),
                                ),
                        ),
                      ),

                      const SizedBox(height: 16),

                      // 提示信息
                      Container(
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                Icon(Icons.info_outline, size: 20, color: Colors.grey[600]),
                                const SizedBox(width: 8),
                                Text(
                                  '温馨提示',
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Colors.grey[800],
                                  ),
                                ),
                              ],
                            ),
                            const SizedBox(height: 8),
                            Text(
                              '• 支付密码为6位纯数字\n• 支付密码用于交易时的安全验证\n• 请妥善保管，不要告诉他人',
                              style: TextStyle(
                                color: Colors.grey[600],
                                height: 1.5,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
    );
  }
}
