import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:geolocator/geolocator.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:path_provider/path_provider.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/contract_signing_service.dart';
import '../widgets/signature_pad.dart';

/// 合同签署页面
class ContractSigningPage extends ConsumerStatefulWidget {
  final String orderNo;

  const ContractSigningPage({
    super.key,
    required this.orderNo,
  });

  @override
  ConsumerState<ContractSigningPage> createState() => _ContractSigningPageState();
}

class _ContractSigningPageState extends ConsumerState<ContractSigningPage> {
  /// 签署任务
  ContractSigningTask? _task;

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

  /// PDF 是否正在加载
  bool _isPdfLoading = true;

  /// PDF 本地文件路径
  String? _pdfPath;

  /// PDF 总页数
  int _totalPages = 0;

  /// 当前页码
  int _currentPage = 0;

  /// 是否已滚动到底部（最后一页）
  bool _hasScrolledToBottom = false;

  /// 是否已确认法律效力
  bool _hasAcknowledged = false;

  /// 是否显示签名面板
  bool _showSignaturePad = false;

  /// 是否正在提交
  bool _isSubmitting = false;

  /// 错误信息
  String? _errorMessage;

  /// PDF 下载进度 (0-100)
  int _downloadProgress = 0;

  /// PDF 下载重试次数
  int _downloadRetryCount = 0;

  /// 倒计时定时器
  Timer? _countdownTimer;

  /// 剩余秒数
  int _remainingSeconds = 0;

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

  @override
  void dispose() {
    _countdownTimer?.cancel();
    // 清理临时 PDF 文件
    if (_pdfPath != null) {
      File(_pdfPath!).delete().catchError((e) => File(_pdfPath!));
    }
    super.dispose();
  }

  /// 加载签署任务（带重试机制，解决竞态问题）
  /// KYC 成功后后端需要通过 Kafka 异步创建合同任务，可能需要较长时间
  Future<void> _loadTask() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    const maxRetries = 15;
    const retryDelay = Duration(seconds: 2);

    for (int attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        final service = ref.read(contractSigningServiceProvider);
        final task = await service.getTask(widget.orderNo);

        setState(() {
          _task = task;
          _isLoading = false;
          _remainingSeconds = task.remainingSeconds;
          _hasScrolledToBottom = task.scrolledToBottomAt != null;
          _hasAcknowledged = task.acknowledgedAt != null;
        });

        // 启动倒计时
        _startCountdown();

        // 加载 PDF
        if (task.status != ContractSigningStatus.signed) {
          _loadPdf();
        }
        return; // 成功，退出重试循环
      } catch (e) {
        debugPrint('[ContractSigningPage] 加载任务失败 (尝试 $attempt/$maxRetries): $e');

        // 如果是"任务不存在"错误且不是最后一次尝试，则等待后重试
        // 这是为了处理 KYC 事件异步创建合同的延迟
        if (attempt < maxRetries && e.toString().contains('不存在')) {
          debugPrint('[ContractSigningPage] 等待 ${retryDelay.inSeconds}s 后重试...');
          await Future.delayed(retryDelay);
          continue;
        }

        // 最后一次尝试或其他错误
        setState(() {
          _isLoading = false;
          _errorMessage = '加载签署任务失败，请稍后重试';
        });
        return;
      }
    }
  }

  /// 加载 PDF 文件
  Future<void> _loadPdf() async {
    setState(() {
      _isPdfLoading = true;
      _downloadProgress = 0;
      _errorMessage = null;
    });

    try {
      final service = ref.read(contractSigningServiceProvider);
      final pdfBytes = await service.downloadContractPdf(
        widget.orderNo,
        onProgress: (received, total) {
          if (total > 0 && mounted) {
            final progress = ((received / total) * 100).round();
            setState(() {
              _downloadProgress = progress;
            });
          }
        },
      );

      // 保存到临时文件
      final tempDir = await getTemporaryDirectory();
      final tempFile = File('${tempDir.path}/contract_${widget.orderNo}.pdf');
      await tempFile.writeAsBytes(pdfBytes);

      if (mounted) {
        setState(() {
          _pdfPath = tempFile.path;
          _isPdfLoading = false;
          _downloadProgress = 100;
        });
      }
    } catch (e) {
      debugPrint('[ContractSigningPage] PDF 加载失败: $e');
      if (mounted) {
        setState(() {
          _isPdfLoading = false;
          _downloadRetryCount++;
          _errorMessage = '加载合同失败，请点击重试';
        });
      }
    }
  }

  /// 启动倒计时
  void _startCountdown() {
    _countdownTimer?.cancel();
    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_remainingSeconds > 0) {
        setState(() {
          _remainingSeconds--;
        });
      } else {
        timer.cancel();
        // 超时处理
        _handleTimeout();
      }
    });
  }

  /// 处理超时
  void _handleTimeout() {
    if (_task?.status != ContractSigningStatus.signed) {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => AlertDialog(
          title: const Text('签署超时'),
          content: const Text('您的签署时间已超时，合同将标记为未签署状态。您可以在后续补签。'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                context.pop(false);
              },
              child: const Text('知道了'),
            ),
          ],
        ),
      );
    }
  }

  /// PDF 页面变化回调
  void _onPageChanged(int? page, int? total) {
    if (page == null || total == null) return;

    setState(() {
      _currentPage = page;
      _totalPages = total;
    });

    // 如果已经翻到最后一页，标记已阅读完成
    if (page == total - 1 && !_hasScrolledToBottom) {
      _markScrollComplete();
    }
  }

  /// 标记已滚动到底部
  Future<void> _markScrollComplete() async {
    if (_hasScrolledToBottom || _task == null) return;

    try {
      final service = ref.read(contractSigningServiceProvider);
      await service.markScrollComplete(widget.orderNo);

      setState(() {
        _hasScrolledToBottom = true;
      });
    } catch (e) {
      debugPrint('标记滚动失败: $e');
    }
  }

  /// 确认法律效力
  Future<void> _acknowledgeContract() async {
    if (_hasAcknowledged || _task == null) return;

    setState(() => _isSubmitting = true);

    try {
      final service = ref.read(contractSigningServiceProvider);
      await service.acknowledgeContract(widget.orderNo);

      setState(() {
        _hasAcknowledged = true;
        _isSubmitting = false;
      });
    } catch (e) {
      setState(() => _isSubmitting = false);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('确认失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  /// 显示签名面板
  void _showSignatureDialog() {
    if (!_hasAcknowledged) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请先确认合同法律效力'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    setState(() => _showSignaturePad = true);
  }

  /// 提交签名
  Future<void> _submitSignature(Uint8List signatureImage, SignatureTraceData traceData) async {
    if (_isSubmitting || _task == null) return;

    // 记录轨迹数据到日志（用于调试）
    debugPrint('[ContractSigningPage] 签名轨迹数据: ${traceData.strokeCount} 笔画, 总时长 ${traceData.totalDuration}ms');

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

    try {
      // 获取设备信息和位置
      String? ipAddress;
      String? deviceInfo;
      String? userAgent;
      double? latitude;
      double? longitude;

      try {
        // 获取设备信息
        final deviceInfoPlugin = DeviceInfoPlugin();
        if (Platform.isAndroid) {
          final androidInfo = await deviceInfoPlugin.androidInfo;
          deviceInfo = '{"platform":"android","model":"${androidInfo.model}","brand":"${androidInfo.brand}","sdk":"${androidInfo.version.sdkInt}"}';
          userAgent = 'Android ${androidInfo.version.release}';
        } else if (Platform.isIOS) {
          final iosInfo = await deviceInfoPlugin.iosInfo;
          deviceInfo = '{"platform":"ios","model":"${iosInfo.model}","name":"${iosInfo.name}","systemVersion":"${iosInfo.systemVersion}"}';
          userAgent = 'iOS ${iosInfo.systemVersion}';
        }

        // 获取位置（需要权限）
        final permission = await Geolocator.checkPermission();
        if (permission == LocationPermission.always || permission == LocationPermission.whileInUse) {
          final position = await Geolocator.getCurrentPosition(
            desiredAccuracy: LocationAccuracy.medium,
          );
          latitude = position.latitude;
          longitude = position.longitude;
        }
      } catch (e) {
        debugPrint('获取设备信息/位置失败: $e');
      }

      final service = ref.read(contractSigningServiceProvider);

      // 转换轨迹数据为 Map
      final traceDataMap = traceData.toJson();

      // 判断是正常签署还是补签
      if (_task!.status == ContractSigningStatus.unsignedTimeout) {
        await service.lateSignContract(
          orderNo: widget.orderNo,
          signatureImage: signatureImage,
          ipAddress: ipAddress,
          deviceInfo: deviceInfo,
          userAgent: userAgent,
          latitude: latitude,
          longitude: longitude,
          signatureTrace: traceDataMap,
        );
      } else {
        await service.signContract(
          orderNo: widget.orderNo,
          signatureImage: signatureImage,
          ipAddress: ipAddress,
          deviceInfo: deviceInfo,
          userAgent: userAgent,
          latitude: latitude,
          longitude: longitude,
          signatureTrace: traceDataMap,
        );
      }

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

      if (mounted) {
        // 保存外层 context 的 canPop 状态（对话框内的 context 不同）
        final outerContext = context;
        final canPopBack = outerContext.canPop();

        // 显示成功对话框
        await showDialog(
          context: context,
          barrierDismissible: false,
          builder: (dialogContext) => AlertDialog(
            title: const Row(
              children: [
                Icon(Icons.check_circle, color: Colors.green, size: 28),
                SizedBox(width: 8),
                Text('签署成功'),
              ],
            ),
            content: const Text('合同已签署完成，感谢您的认种！'),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(dialogContext).pop(); // 关闭对话框
                  // 如果可以 pop（说明是从待办操作或待签合同列表 push 进来的），返回 true
                  // 否则跳转到个人页面
                  if (canPopBack) {
                    outerContext.pop(true);
                  } else {
                    outerContext.go('/profile');
                  }
                },
                child: const Text('完成'),
              ),
            ],
          ),
        );
      }
    } catch (e) {
      setState(() => _isSubmitting = false);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('签署失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  /// 格式化剩余时间
  String _formatRemainingTime() {
    final hours = _remainingSeconds ~/ 3600;
    final minutes = (_remainingSeconds % 3600) ~/ 60;
    final seconds = _remainingSeconds % 60;
    return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }

  @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: _showSignaturePad
              ? _buildSignaturePad()
              : Column(
                  children: [
                    _buildHeader(),
                    if (!_isLoading && _task != null) _buildCountdownBar(),
                    Expanded(child: _buildContent()),
                    if (!_isLoading && _task != null) _buildBottomActions(),
                  ],
                ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        color: const Color(0xFFFFF7E6).withValues(alpha: 0.8),
      ),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => context.pop(false),
            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(false),
            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 _buildCountdownBar() {
    final isTimeout = _remainingSeconds <= 0;
    final isUrgent = _remainingSeconds < 3600; // 小于1小时

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: isTimeout
            ? const Color(0xFFFFEBEE)
            : isUrgent
                ? const Color(0xFFFFF3E0)
                : const Color(0xFFE8F5E9),
        border: Border(
          bottom: BorderSide(
            color: isTimeout
                ? const Color(0xFFE53935)
                : isUrgent
                    ? const Color(0xFFFF9800)
                    : const Color(0xFF4CAF50),
            width: 1,
          ),
        ),
      ),
      child: Row(
        children: [
          Icon(
            isTimeout
                ? Icons.error_outline
                : isUrgent
                    ? Icons.access_time
                    : Icons.timer,
            color: isTimeout
                ? const Color(0xFFE53935)
                : isUrgent
                    ? const Color(0xFFFF9800)
                    : const Color(0xFF4CAF50),
            size: 20,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              isTimeout
                  ? '签署已超时，请尽快补签'
                  : '请在 ${_formatRemainingTime()} 内完成签署',
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
                color: isTimeout
                    ? const Color(0xFFE53935)
                    : isUrgent
                        ? const Color(0xFFE65100)
                        : const Color(0xFF2E7D32),
              ),
            ),
          ),
          // 页码显示
          if (_totalPages > 0)
            Text(
              '${_currentPage + 1}/$_totalPages',
              style: const TextStyle(
                fontSize: 12,
                color: Color(0xFF666666),
              ),
            ),
        ],
      ),
    );
  }

  /// 构建内容区域
  Widget _buildContent() {
    if (_isLoading) {
      return const Center(
        child: CircularProgressIndicator(color: Color(0xFFD4AF37)),
      );
    }

    if (_errorMessage != null) {
      // 判断是任务加载错误还是 PDF 下载错误
      final isPdfError = _task != null && _pdfPath == null;
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                isPdfError ? Icons.cloud_download_outlined : Icons.error_outline,
                color: isPdfError ? const Color(0xFFD4AF37) : Colors.red,
                size: 56,
              ),
              const SizedBox(height: 16),
              Text(
                _errorMessage!,
                style: TextStyle(
                  fontSize: 16,
                  color: isPdfError ? const Color(0xFF666666) : Colors.red,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 24),
              ElevatedButton.icon(
                onPressed: isPdfError ? _loadPdf : _loadTask,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFFD4AF37),
                  padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 12),
                ),
                icon: const Icon(Icons.refresh, color: Colors.white),
                label: const Text(
                  '重试',
                  style: TextStyle(color: Colors.white, fontSize: 16),
                ),
              ),
              if (isPdfError && _downloadRetryCount > 0)
                Padding(
                  padding: const EdgeInsets.only(top: 12),
                  child: Text(
                    '已自动重试 $_downloadRetryCount 次',
                    style: const TextStyle(
                      fontSize: 12,
                      color: Color(0xFF999999),
                    ),
                  ),
                ),
            ],
          ),
        ),
      );
    }

    if (_task == null) {
      return const Center(child: Text('未找到签署任务'));
    }

    // 如果已签署，显示签署完成信息
    if (_task!.status == ContractSigningStatus.signed) {
      return _buildSignedContent();
    }

    // PDF 加载中
    if (_isPdfLoading || _pdfPath == null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 进度圆环
            SizedBox(
              width: 80,
              height: 80,
              child: Stack(
                alignment: Alignment.center,
                children: [
                  CircularProgressIndicator(
                    value: _downloadProgress > 0 ? _downloadProgress / 100 : null,
                    color: const Color(0xFFD4AF37),
                    strokeWidth: 6,
                    backgroundColor: const Color(0xFFE0E0E0),
                  ),
                  if (_downloadProgress > 0)
                    Text(
                      '$_downloadProgress%',
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: Color(0xFFD4AF37),
                      ),
                    ),
                ],
              ),
            ),
            const SizedBox(height: 16),
            Text(
              _downloadProgress > 0 ? '正在下载合同 $_downloadProgress%' : '正在加载合同...',
              style: const TextStyle(
                fontSize: 14,
                color: Color(0xFF666666),
              ),
            ),
            if (_downloadRetryCount > 0)
              Padding(
                padding: const EdgeInsets.only(top: 8),
                child: Text(
                  '正在重试 (第 $_downloadRetryCount 次)',
                  style: const TextStyle(
                    fontSize: 12,
                    color: Color(0xFF999999),
                  ),
                ),
              ),
          ],
        ),
      );
    }

    // PDF 查看器
    return Column(
      children: [
        // 合同信息卡片
        _buildContractInfo(),
        // PDF 内容
        Expanded(
          child: Container(
            margin: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.1),
                  blurRadius: 6,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: PDFView(
                filePath: _pdfPath!,
                enableSwipe: true,
                swipeHorizontal: false,
                autoSpacing: true,
                pageFling: true,
                pageSnap: true,
                fitPolicy: FitPolicy.WIDTH,
                onRender: (pages) {
                  setState(() {
                    _totalPages = pages ?? 0;
                  });
                },
                onPageChanged: _onPageChanged,
                onError: (error) {
                  debugPrint('PDF 加载错误: $error');
                  setState(() {
                    _errorMessage = 'PDF 加载失败: $error';
                  });
                },
              ),
            ),
          ),
        ),
        // 翻页提示
        if (!_hasScrolledToBottom && _totalPages > 0)
          Container(
            padding: const EdgeInsets.symmetric(vertical: 8),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(Icons.swipe, color: Color(0xFFD4AF37), size: 20),
                const SizedBox(width: 8),
                Text(
                  '请滑动至最后一页阅读完整合同 (${_currentPage + 1}/$_totalPages)',
                  style: const TextStyle(
                    color: Color(0xFFD4AF37),
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ),
      ],
    );
  }

  /// 构建已签署内容
  Widget _buildSignedContent() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 100,
              height: 100,
              decoration: BoxDecoration(
                color: const Color(0xFFE8F5E9),
                borderRadius: BorderRadius.circular(50),
              ),
              child: const Icon(
                Icons.check_circle,
                color: Color(0xFF4CAF50),
                size: 60,
              ),
            ),
            const SizedBox(height: 24),
            const Text(
              '合同签署完成',
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
                color: Color(0xFF2E7D32),
              ),
            ),
            const SizedBox(height: 8),
            Text(
              '签署时间: ${_formatDateTime(_task!.signedAt)}',
              style: const TextStyle(
                fontSize: 14,
                color: Color(0xFF666666),
              ),
            ),
            const SizedBox(height: 32),
            ElevatedButton(
              onPressed: () => context.pop(true),
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFD4AF37),
                padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
              child: const Text(
                '返回',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 格式化日期时间
  String _formatDateTime(DateTime? dateTime) {
    if (dateTime == null) return '-';
    final local = dateTime.toLocal();
    return '${local.year}-${local.month.toString().padLeft(2, '0')}-${local.day.toString().padLeft(2, '0')} ${local.hour.toString().padLeft(2, '0')}:${local.minute.toString().padLeft(2, '0')}';
  }

  /// 构建合同信息卡片
  Widget _buildContractInfo() {
    return Container(
      margin: const EdgeInsets.all(8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.1),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '合同编号: ${_task!.contractNo}',
                  style: const TextStyle(
                    fontSize: 12,
                    color: Color(0xFF666666),
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  '${_task!.treeCount} 棵榴莲树 · ${_task!.totalAmount.toStringAsFixed(2)} 绿积分',
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFF5D4037),
                  ),
                ),
              ],
            ),
          ),
          Text(
            '${_task!.provinceName} ${_task!.cityName}',
            style: const TextStyle(
              fontSize: 12,
              color: Color(0xFF999999),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建底部操作区
  Widget _buildBottomActions() {
    if (_task!.status == ContractSigningStatus.signed) {
      return const SizedBox.shrink();
    }

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.1),
            blurRadius: 10,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 法律效力确认复选框
          if (!_hasAcknowledged)
            GestureDetector(
              onTap: _hasScrolledToBottom ? _acknowledgeContract : null,
              child: Container(
                padding: const EdgeInsets.symmetric(vertical: 12),
                child: Row(
                  children: [
                    Container(
                      width: 24,
                      height: 24,
                      decoration: BoxDecoration(
                        color: const Color(0xFFE0E0E0),
                        borderRadius: BorderRadius.circular(4),
                        border: _hasScrolledToBottom
                            ? Border.all(color: const Color(0xFFD4AF37), width: 2)
                            : null,
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Text(
                        '我已阅读并同意上述协议，确认其具有法律效力',
                        style: TextStyle(
                          fontSize: 14,
                          color: _hasScrolledToBottom ? const Color(0xFF333333) : const Color(0xFF999999),
                        ),
                      ),
                    ),
                    if (!_hasScrolledToBottom)
                      const Text(
                        '(请先阅读完合同)',
                        style: TextStyle(
                          fontSize: 12,
                          color: Color(0xFF999999),
                        ),
                      ),
                  ],
                ),
              ),
            ),
          if (_hasAcknowledged)
            Container(
              padding: const EdgeInsets.symmetric(vertical: 8),
              child: const Row(
                children: [
                  Icon(Icons.check_circle, color: Color(0xFF4CAF50), size: 20),
                  SizedBox(width: 8),
                  Text(
                    '已确认协议法律效力',
                    style: TextStyle(
                      fontSize: 14,
                      color: Color(0xFF4CAF50),
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            ),
          const SizedBox(height: 12),
          // 签署按钮
          GestureDetector(
            onTap: _hasAcknowledged && !_isSubmitting ? _showSignatureDialog : null,
            child: Container(
              width: double.infinity,
              height: 56,
              decoration: BoxDecoration(
                color: _hasAcknowledged
                    ? const Color(0xFFD4AF37)
                    : const Color(0xFFD4AF37).withValues(alpha: 0.5),
                borderRadius: BorderRadius.circular(12),
                boxShadow: _hasAcknowledged
                    ? [
                        BoxShadow(
                          color: const Color(0xFFD4AF37).withValues(alpha: 0.3),
                          blurRadius: 15,
                          offset: const Offset(0, 8),
                        ),
                      ]
                    : 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.w600,
                          color: Colors.white,
                        ),
                      ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建签名面板
  Widget _buildSignaturePad() {
    // 横屏签名面板，不显示顶部 header
    return SignaturePad(
      onSubmit: _submitSignature,
      onCancel: () => setState(() => _showSignaturePad = false),
      userName: _task?.userRealName,
    );
  }
}
