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/di/injection_container.dart';
import '../../../../routes/route_paths.dart';

// ============================================
// [2026-02-19] 树转让发起页（纯新增）
// ============================================
//
// 用户发起树转让的表单页面：
// - 输入买方账号
// - 输入转让棵数
// - 确认发起转让
// 注：价格线下柜台签合同交易，APP 仅完成系统层面所有权 + 算力转移
//
// === 回滚方式 ===
// 删除 features/transfer/ 目录

/// 转让发起页
class TransferInitiatePage extends ConsumerStatefulWidget {
  const TransferInitiatePage({super.key});

  @override
  ConsumerState<TransferInitiatePage> createState() => _TransferInitiatePageState();
}

class _TransferInitiatePageState extends ConsumerState<TransferInitiatePage> {
  final _buyerController = TextEditingController();
  final _treeCountController = TextEditingController(text: '1');
  bool _isSubmitting = false;
  String? _errorMessage;

  @override
  void dispose() {
    _buyerController.dispose();
    _treeCountController.dispose();
    super.dispose();
  }

  int get _treeCount => int.tryParse(_treeCountController.text) ?? 1;

  Future<void> _handleSubmit() async {
    final buyer = _buyerController.text.trim();
    if (buyer.isEmpty) {
      setState(() => _errorMessage = '请输入买方账号');
      return;
    }
    if (_treeCount <= 0) {
      setState(() => _errorMessage = '请输入有效的转让棵数');
      return;
    }

    // 确认对话框
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        backgroundColor: const Color(0xFFFFF7E6),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        title: const Text(
          '确认发起转让',
          style: TextStyle(color: Color(0xFF5D4037), fontWeight: FontWeight.w700),
        ),
        content: Text(
          '买方账号: $buyer\n'
          '转让棵数: $_treeCount 棵\n\n'
          '确认后系统将完成树所有权变更及算力调整。\n'
          '交易价格请线下柜台签署合同确定。',
          style: const TextStyle(color: Color(0xFF5D4037), fontSize: 14, height: 1.6),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx, false),
            child: const Text('取消', style: TextStyle(color: Color(0xFF745D43))),
          ),
          ElevatedButton(
            onPressed: () => Navigator.pop(ctx, true),
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFFD4AF37),
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
            ),
            child: const Text('确认发起'),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

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

    try {
      final service = ref.read(transferServiceProvider);
      final order = await service.createTransfer(
        buyerAccountSequence: buyer,
        plantingOrderNos: [], // 由后端根据棵数自动选择
        treeCount: _treeCount,
      );

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('转让发起成功！等待卖方确认'),
            backgroundColor: Color(0xFF52C41A),
          ),
        );
        // 跳转到详情页
        context.pushReplacement('${RoutePaths.transferDetail}/${order.transferOrderNo}');
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = e.toString();
          _isSubmitting = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFFFFF7E6),
              Color(0xFFEAE0C8),
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              _buildHeader(),
              Expanded(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 说明卡片
                      Container(
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: const Color(0xFFD4AF37).withValues(alpha: 0.1),
                          borderRadius: BorderRadius.circular(12),
                          border: Border.all(color: const Color(0xFFD4AF37).withValues(alpha: 0.3)),
                        ),
                        child: const Row(
                          children: [
                            Icon(Icons.info_outline, color: Color(0xFFD4AF37), size: 20),
                            SizedBox(width: 8),
                            Expanded(
                              child: Text(
                                '转让已认种的果树所有权。系统将自动完成所有权变更及算力调整，交易价格请线下柜台签署合同确定。',
                                style: TextStyle(fontSize: 13, color: Color(0xFF8B5A2B)),
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 24),

                      // 买方账号
                      _buildLabel('买方账号'),
                      const SizedBox(height: 8),
                      _buildTextField(
                        controller: _buyerController,
                        hintText: '输入买方账号（如 D25121400002）',
                        keyboardType: TextInputType.text,
                      ),
                      const SizedBox(height: 20),

                      // 转让棵数
                      _buildLabel('转让棵数'),
                      const SizedBox(height: 8),
                      _buildTextField(
                        controller: _treeCountController,
                        hintText: '输入棵数',
                        keyboardType: TextInputType.number,
                        inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                        onChanged: (_) => setState(() {}),
                      ),
                      const SizedBox(height: 24),

                      // 错误信息
                      if (_errorMessage != null) ...[
                        Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: const Color(0xFFFFF3E0),
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(color: const Color(0xFFE65100)),
                          ),
                          child: Row(
                            children: [
                              const Icon(Icons.error_outline, color: Color(0xFFE65100), size: 16),
                              const SizedBox(width: 8),
                              Expanded(
                                child: Text(_errorMessage!, style: const TextStyle(color: Color(0xFFE65100), fontSize: 13)),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(height: 16),
                      ],

                      // 提交按钮
                      GestureDetector(
                        onTap: _isSubmitting ? null : _handleSubmit,
                        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: !_isSubmitting
                                ? const [
                                    BoxShadow(
                                      color: Color(0x1A000000),
                                      blurRadius: 15,
                                      offset: Offset(0, 10),
                                    ),
                                    BoxShadow(
                                      color: Color(0x1A000000),
                                      blurRadius: 6,
                                      offset: Offset(0, 4),
                                    ),
                                  ]
                                : null,
                          ),
                          child: Center(
                            child: _isSubmitting
                                ? const SizedBox(
                                    width: 24,
                                    height: 24,
                                    child: CircularProgressIndicator(
                                      strokeWidth: 2,
                                      color: Colors.white,
                                    ),
                                  )
                                : const Text(
                                    '发起转让',
                                    style: TextStyle(
                                      fontSize: 18,
                                      fontFamily: 'Inter',
                                      fontWeight: FontWeight.w500,
                                      height: 1.56,
                                      color: Colors.white,
                                    ),
                                  ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => context.pop(),
            child: Container(
              width: 32,
              height: 32,
              alignment: Alignment.center,
              child: const Icon(
                Icons.arrow_back_ios,
                color: Color(0xFFD4AF37),
                size: 20,
              ),
            ),
          ),
          const SizedBox(width: 4),
          GestureDetector(
            onTap: () => context.pop(),
            child: const Text(
              '返回',
              style: TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                height: 1.5,
                color: Color(0xFFD4AF37),
              ),
            ),
          ),
          const SizedBox(width: 42),
          const Expanded(
            child: Text(
              '发起转让',
              style: TextStyle(
                fontSize: 18,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w700,
                height: 1.25,
                letterSpacing: -0.27,
                color: Color(0xFF5D4037),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLabel(String text) {
    return Text(
      text,
      style: const TextStyle(
        fontSize: 16,
        fontFamily: 'Inter',
        fontWeight: FontWeight.w500,
        height: 1.5,
        color: Color(0xFF5D4037),
      ),
    );
  }

  Widget _buildTextField({
    required TextEditingController controller,
    required String hintText,
    TextInputType? keyboardType,
    List<TextInputFormatter>? inputFormatters,
    ValueChanged<String>? onChanged,
  }) {
    return TextField(
      controller: controller,
      keyboardType: keyboardType,
      inputFormatters: inputFormatters,
      onChanged: onChanged,
      style: const TextStyle(color: Color(0xFF5D4037), fontSize: 15, fontFamily: 'Inter'),
      decoration: InputDecoration(
        hintText: hintText,
        hintStyle: const TextStyle(color: Color(0xFF745D43)),
        filled: true,
        fillColor: const Color(0x99FFFFFF),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: const BorderSide(color: Color(0xFFEAE0C8)),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: const BorderSide(color: Color(0xFFEAE0C8)),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: const BorderSide(color: Color(0xFFD4AF37), width: 2),
        ),
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
      ),
    );
  }

}
