import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:go_router/go_router.dart';
import 'package:path_provider/path_provider.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/pre_planting_service.dart';
import '../../../../routes/route_paths.dart';
import '../../../contract_signing/presentation/widgets/signature_pad.dart';

/// 预种合并合同签署页面
///
/// 流程与普通认种完全一致：
/// PDF 展示 → 滚动到底部 → 确认法律效力 → 手写签名 → 提交
class PrePlantingMergeSigningPage extends ConsumerStatefulWidget {
  final String mergeNo;

  const PrePlantingMergeSigningPage({
    super.key,
    required this.mergeNo,
  });

  @override
  ConsumerState<PrePlantingMergeSigningPage> createState() =>
      _PrePlantingMergeSigningPageState();
}

class _PrePlantingMergeSigningPageState
    extends ConsumerState<PrePlantingMergeSigningPage> {
  bool _isLoading = true;
  bool _isPdfLoading = true;
  String? _pdfPath;
  int _totalPages = 0;
  int _currentPage = 0;
  bool _hasScrolledToBottom = false;
  bool _hasAcknowledged = false;
  bool _isSubmitting = false;
  bool _showSignaturePad = false;
  String? _errorMessage;
  bool _isKycRequired = false;
  int _downloadProgress = 0;
  int _downloadRetryCount = 0;

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

  @override
  void dispose() {
    if (_pdfPath != null) {
      File(_pdfPath!).delete().catchError((e) => File(_pdfPath!));
    }
    super.dispose();
  }

  Future<void> _loadPdf() async {
    setState(() {
      _isLoading = false;
      _isPdfLoading = true;
      _downloadProgress = 0;
      _errorMessage = null;
    });

    try {
      final service = ref.read(prePlantingServiceProvider);
      final pdfBytes = await service.downloadMergeContractPdf(
        widget.mergeNo,
        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}/merge_contract_${widget.mergeNo}.pdf');
      await tempFile.writeAsBytes(pdfBytes);

      if (mounted) {
        setState(() {
          _pdfPath = tempFile.path;
          _isPdfLoading = false;
          _downloadProgress = 100;
        });
      }
    } catch (e) {
      debugPrint('[MergeSigningPage] PDF加载失败: $e');
      if (mounted) {
        final msg = e.toString();
        final isKyc = msg.contains('实名认证') || msg.contains('400');
        setState(() {
          _isPdfLoading = false;
          _isKycRequired = isKyc;
          _errorMessage = isKyc ? '请先完成实名认证方可查看和签署合同' : '加载合同失败，请点击重试';
          if (!isKyc) _downloadRetryCount++;
        });
      }
    }
  }

  void _onPageChanged(int? page, int? total) {
    if (page == null || total == null) return;
    setState(() {
      _currentPage = page;
      _totalPages = total;
    });
    if (page == total - 1 && !_hasScrolledToBottom) {
      setState(() => _hasScrolledToBottom = true);
    }
  }

  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) return;

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

    try {
      final service = ref.read(prePlantingServiceProvider);
      await service.signMergeContract(widget.mergeNo);

      setState(() => _isSubmitting = false);

      if (mounted) {
        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();
                  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,
          ),
        );
      }
    }
  }

  @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 && _pdfPath != null) _buildInfoBar(),
                    Expanded(child: _buildContent()),
                    if (!_isLoading && !_isPdfLoading && _errorMessage == 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 _buildInfoBar() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
      decoration: const BoxDecoration(
        color: Color(0xFFE8F5E9),
        border:
            Border(bottom: BorderSide(color: Color(0xFF4CAF50), width: 1)),
      ),
      child: Row(
        children: [
          const Icon(Icons.park_outlined, color: Color(0xFF4CAF50), size: 18),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              '合并编号: ${widget.mergeNo}',
              style: const TextStyle(
                fontSize: 13,
                color: Color(0xFF2E7D32),
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          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) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                _isKycRequired ? Icons.person_off_outlined : Icons.cloud_download_outlined,
                color: _isKycRequired ? Colors.red : const Color(0xFFD4AF37),
                size: 56,
              ),
              const SizedBox(height: 16),
              Text(
                _errorMessage!,
                style: const TextStyle(fontSize: 16, color: Color(0xFF666666)),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 24),
              if (_isKycRequired)
                ElevatedButton.icon(
                  onPressed: () => context.push(RoutePaths.kycEntry),
                  style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.red,
                      padding: const EdgeInsets.symmetric(
                          horizontal: 32, vertical: 12)),
                  icon: const Icon(Icons.verified_user, color: Colors.white),
                  label: const Text('去完成实名认证',
                      style: TextStyle(color: Colors.white, fontSize: 16)),
                )
              else
                ElevatedButton.icon(
                  onPressed: _loadPdf,
                  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 (!_isKycRequired && _downloadRetryCount > 0)
                Padding(
                  padding: const EdgeInsets.only(top: 12),
                  child: Text(
                    '已自动重试 $_downloadRetryCount 次',
                    style: const TextStyle(
                        fontSize: 12, color: Color(0xFF999999)),
                  ),
                ),
            ],
          ),
        ),
      );
    }

    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)),
            ),
          ],
        ),
      );
    }

    return Column(
      children: [
        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) {
                  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 _buildBottomActions() {
    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
                  ? () => setState(() => _hasAcknowledged = true)
                  : 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(0xFF4CAF50)
                    : const Color(0xFF4CAF50).withValues(alpha: 0.5),
                borderRadius: BorderRadius.circular(12),
                boxShadow: _hasAcknowledged
                    ? [
                        BoxShadow(
                          color:
                              const Color(0xFF4CAF50).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() {
    return SignaturePad(
      onSubmit: _submitSignature,
      onCancel: () => setState(() => _showSignaturePad = false),
    );
  }
}
