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 '../../../../core/services/contract_signing_service.dart';
import '../../../../core/services/pre_planting_service.dart';
import '../../../../routes/route_paths.dart';

/// 待签署合同列表页面
/// 用于 App 启动时检查并强制用户签署未完成的合同
/// 包含：普通认种合同 + 预种合并合同
class PendingContractsPage extends ConsumerStatefulWidget {
  /// 是否为强制模式（不允许跳过）
  final bool forceSign;

  const PendingContractsPage({
    super.key,
    this.forceSign = false,
  });

  @override
  ConsumerState<PendingContractsPage> createState() => _PendingContractsPageState();
}

class _PendingContractsPageState extends ConsumerState<PendingContractsPage> {
  List<ContractSigningTask> _unsignedTasks = [];
  List<PrePlantingMerge> _pendingMerges = [];
  bool _isLoading = true;
  String? _errorMessage;

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

  Future<void> _loadTasks() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final contractService = ref.read(contractSigningServiceProvider);
      final prePlantingService = ref.read(prePlantingServiceProvider);

      // 并行加载：普通认种未签合同 + 预种待签合并
      final tasksFuture = contractService.getUnsignedTasks();
      final mergesFuture = prePlantingService.getMyMerges();
      final tasks = await tasksFuture;
      final allMerges = await mergesFuture;
      final pendingMerges = allMerges
          .where((m) => m.contractStatus == PrePlantingContractStatus.pending)
          .toList();

      setState(() {
        _unsignedTasks = tasks;
        _pendingMerges = pendingMerges;
        _isLoading = false;
      });

      // 如果没有任何待签署任务，自动返回
      if (_unsignedTasks.isEmpty && _pendingMerges.isEmpty) {
        if (mounted) {
          context.pop(true);
        }
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
        _errorMessage = '加载失败: $e';
      });
    }
  }

  /// 签署普通认种合同
  Future<void> _signContract(ContractSigningTask task) async {
    final result = await context.push<bool>(
      '${RoutePaths.contractSigning}/${task.orderNo}',
    );

    if (result == true) {
      // 签署成功，刷新列表
      _loadTasks();
    }
  }

  /// 签署预种合并合同（跳转到合并详情页）
  Future<void> _signPrePlantingMerge(PrePlantingMerge merge) async {
    await context.push('${RoutePaths.prePlantingMergeSigning}/${merge.mergeNo}');
    // 返回后刷新，合并可能已签署
    _loadTasks();
  }

  /// 跳过（仅非强制模式）
  void _skip() {
    if (!widget.forceSign) {
      context.pop(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: _buildContent()),
              if (!widget.forceSign && !_isLoading) _buildSkipButton(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          const Icon(
            Icons.description_outlined,
            color: Color(0xFFD4AF37),
            size: 48,
          ),
          const SizedBox(height: 12),
          const Text(
            '待签署合同',
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: Color(0xFF5D4037),
            ),
          ),
          const SizedBox(height: 8),
          Text(
            widget.forceSign
                ? '您有未签署的认种合同，请完成签署后继续使用'
                : '以下合同待您签署',
            style: const TextStyle(
              fontSize: 14,
              color: Color(0xFF666666),
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildContent() {
    if (_isLoading) {
      return const Center(
        child: CircularProgressIndicator(color: Color(0xFFD4AF37)),
      );
    }

    if (_errorMessage != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, color: Colors.red, size: 48),
            const SizedBox(height: 16),
            Text(
              _errorMessage!,
              style: const TextStyle(fontSize: 16, color: Colors.red),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _loadTasks,
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFD4AF37),
              ),
              child: const Text('重试', style: TextStyle(color: Colors.white)),
            ),
          ],
        ),
      );
    }

    if (_unsignedTasks.isEmpty && _pendingMerges.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.check_circle_outline, color: Color(0xFF4CAF50), size: 64),
            SizedBox(height: 16),
            Text(
              '所有合同已签署完成',
              style: TextStyle(
                fontSize: 18,
                color: Color(0xFF4CAF50),
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _loadTasks,
      color: const Color(0xFFD4AF37),
      child: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          ..._unsignedTasks.map((task) => _buildTaskCard(task)),
          ..._pendingMerges.map((merge) => _buildMergeCard(merge)),
        ],
      ),
    );
  }

  Widget _buildTaskCard(ContractSigningTask task) {
    final isTimeout = task.status == ContractSigningStatus.unsignedTimeout;
    final isUrgent = !isTimeout && task.remainingSeconds < 3600;

    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.1),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
        border: isTimeout
            ? Border.all(color: const Color(0xFFE53935), width: 1)
            : isUrgent
                ? Border.all(color: const Color(0xFFFF9800), width: 1)
                : null,
      ),
      child: InkWell(
        onTap: () => _signContract(task),
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '订单号: ${task.orderNo}',
                          style: const TextStyle(
                            fontSize: 14,
                            color: Color(0xFF666666),
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          '${task.treeCount} 棵榴莲树',
                          style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Color(0xFF5D4037),
                          ),
                        ),
                      ],
                    ),
                  ),
                  _buildStatusBadge(task),
                ],
              ),
              const SizedBox(height: 12),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '金额: ${task.totalAmount.toStringAsFixed(2)} 绿积分',
                    style: const TextStyle(
                      fontSize: 14,
                      color: Color(0xFFD4AF37),
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  Text(
                    '${task.provinceName} ${task.cityName}',
                    style: const TextStyle(
                      fontSize: 14,
                      color: Color(0xFF999999),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 12),
              if (isTimeout)
                _buildStatusHint(
                  color: const Color(0xFFFFEBEE),
                  icon: Icons.warning_amber_rounded,
                  iconColor: const Color(0xFFE53935),
                  text: '签署已超时，请尽快补签',
                  textColor: const Color(0xFFE53935),
                )
              else if (isUrgent)
                _buildStatusHint(
                  color: const Color(0xFFFFF3E0),
                  icon: Icons.access_time,
                  iconColor: const Color(0xFFFF9800),
                  text: '剩余 ${_formatRemainingTime(task.remainingSeconds)}',
                  textColor: const Color(0xFFE65100),
                )
              else
                _buildStatusHint(
                  color: const Color(0xFFE3F2FD),
                  icon: Icons.timer,
                  iconColor: const Color(0xFF1976D2),
                  text: '剩余 ${_formatRemainingTime(task.remainingSeconds)}',
                  textColor: const Color(0xFF1976D2),
                ),
              const SizedBox(height: 12),
              _buildSignButton(
                label: isTimeout ? '立即补签' : '立即签署',
                color: isTimeout ? const Color(0xFFE53935) : const Color(0xFFD4AF37),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 预种合并待签卡片
  Widget _buildMergeCard(PrePlantingMerge merge) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.1),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
        border: Border.all(color: const Color(0xFF4CAF50), width: 1),
      ),
      child: InkWell(
        onTap: () => _signPrePlantingMerge(merge),
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '合并编号: ${merge.mergeNo}',
                          style: const TextStyle(
                            fontSize: 14,
                            color: Color(0xFF666666),
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          '${merge.treeCount} 棵预种合并树',
                          style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Color(0xFF5D4037),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                    decoration: BoxDecoration(
                      color: const Color(0xFFE8F5E9),
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: const Text(
                      '待签署',
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                        color: Color(0xFF2E7D32),
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 12),
              _buildStatusHint(
                color: const Color(0xFFE8F5E9),
                icon: Icons.park_outlined,
                iconColor: const Color(0xFF4CAF50),
                text: '10 份预种份额已合并为 ${merge.treeCount} 棵树，请签署合同以开启挖矿',
                textColor: const Color(0xFF2E7D32),
              ),
              const SizedBox(height: 12),
              _buildSignButton(
                label: '立即签署',
                color: const Color(0xFF4CAF50),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildStatusHint({
    required Color color,
    required IconData icon,
    required Color iconColor,
    required String text,
    required Color textColor,
  }) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Icon(icon, color: iconColor, size: 16),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              text,
              style: TextStyle(fontSize: 12, color: textColor),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSignButton({required String label, required Color color}) {
    return Container(
      width: double.infinity,
      height: 44,
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Center(
        child: Text(
          label,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  Widget _buildStatusBadge(ContractSigningTask task) {
    Color bgColor;
    Color textColor;
    String text;

    switch (task.status) {
      case ContractSigningStatus.pending:
        bgColor = const Color(0xFFE3F2FD);
        textColor = const Color(0xFF1976D2);
        text = '待签署';
        break;
      case ContractSigningStatus.scrolled:
        bgColor = const Color(0xFFFFF3E0);
        textColor = const Color(0xFFE65100);
        text = '阅读中';
        break;
      case ContractSigningStatus.acknowledged:
        bgColor = const Color(0xFFE8F5E9);
        textColor = const Color(0xFF2E7D32);
        text = '待签名';
        break;
      case ContractSigningStatus.unsignedTimeout:
        bgColor = const Color(0xFFFFEBEE);
        textColor = const Color(0xFFE53935);
        text = '已超时';
        break;
      default:
        bgColor = const Color(0xFFF5F5F5);
        textColor = const Color(0xFF666666);
        text = '未知';
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(20),
      ),
      child: Text(
        text,
        style: TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.w600,
          color: textColor,
        ),
      ),
    );
  }

  String _formatRemainingTime(int seconds) {
    if (seconds <= 0) return '已超时';

    final hours = seconds ~/ 3600;
    final minutes = (seconds % 3600) ~/ 60;

    if (hours > 0) {
      return '$hours 小时 $minutes 分钟';
    } else {
      return '$minutes 分钟';
    }
  }

  Widget _buildSkipButton() {
    return Container(
      padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
      child: TextButton(
        onPressed: _skip,
        child: const Text(
          '稍后再签',
          style: TextStyle(
            fontSize: 16,
            color: Color(0xFF999999),
          ),
        ),
      ),
    );
  }
}
