import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// 签名轨迹点数据
class SignaturePoint {
  final double x;
  final double y;
  final int timestamp; // 毫秒时间戳

  SignaturePoint({
    required this.x,
    required this.y,
    required this.timestamp,
  });

  Map<String, dynamic> toJson() => {
        'x': x,
        'y': y,
        't': timestamp,
      };
}

/// 签名笔画数据
class SignatureStroke {
  final List<SignaturePoint> points;
  final int startTime;
  final int endTime;

  SignatureStroke({
    required this.points,
    required this.startTime,
    required this.endTime,
  });

  Map<String, dynamic> toJson() => {
        'points': points.map((p) => p.toJson()).toList(),
        'startTime': startTime,
        'endTime': endTime,
      };
}

/// 签名轨迹数据（用于法律凭证）
class SignatureTraceData {
  final List<SignatureStroke> strokes;
  final int totalDuration; // 总签名时长（毫秒）
  final int strokeCount; // 笔画数量

  SignatureTraceData({
    required this.strokes,
    required this.totalDuration,
    required this.strokeCount,
  });

  Map<String, dynamic> toJson() => {
        'strokes': strokes.map((s) => s.toJson()).toList(),
        'totalDuration': totalDuration,
        'strokeCount': strokeCount,
      };
}

/// 签名面板组件
class SignaturePad extends StatefulWidget {
  final Function(Uint8List, SignatureTraceData) onSubmit;
  final VoidCallback onCancel;
  final String? userName; // 用户姓名，用于显示参照

  const SignaturePad({
    super.key,
    required this.onSubmit,
    required this.onCancel,
    this.userName,
  });

  @override
  State<SignaturePad> createState() => _SignaturePadState();
}

class _SignaturePadState extends State<SignaturePad> {
  /// 签名路径列表（用于绘制）
  final List<List<Offset>> _strokes = [];

  /// 当前笔画
  List<Offset> _currentStroke = [];

  /// 签名轨迹数据（带时间戳）
  final List<SignatureStroke> _traceStrokes = [];

  /// 当前笔画的轨迹点
  List<SignaturePoint> _currentTracePoints = [];

  /// 当前笔画开始时间
  int? _currentStrokeStartTime;

  /// 签名开始时间
  int? _signatureStartTime;

  /// 是否有签名
  bool get _hasSignature => _strokes.isNotEmpty || _currentStroke.isNotEmpty;

  @override
  void initState() {
    super.initState();
    // 强制横屏显示
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
  }

  @override
  void dispose() {
    // 恢复竖屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    super.dispose();
  }

  /// 清除签名
  void _clear() {
    setState(() {
      _strokes.clear();
      _currentStroke.clear();
      _traceStrokes.clear();
      _currentTracePoints.clear();
      _currentStrokeStartTime = null;
      _signatureStartTime = null;
    });
  }

  /// 提交签名
  Future<void> _submit() async {
    if (!_hasSignature) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请在签名区域签名'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    // 将签名转换为图片
    final image = await _renderSignatureImage();
    if (image != null) {
      // 构建轨迹数据
      final now = DateTime.now().millisecondsSinceEpoch;
      final totalDuration = _signatureStartTime != null ? now - _signatureStartTime! : 0;
      final traceData = SignatureTraceData(
        strokes: _traceStrokes,
        totalDuration: totalDuration,
        strokeCount: _traceStrokes.length,
      );
      widget.onSubmit(image, traceData);
    }
  }

  /// 渲染签名为图片
  Future<Uint8List?> _renderSignatureImage() async {
    try {
      // 创建画布
      // 尺寸比例需要匹配PDF签名字段比例（约92:51 ≈ 1.8:1）
      // 使用较大尺寸保证清晰度
      const width = 460.0;
      const height = 255.0;

      final recorder = ui.PictureRecorder();
      final canvas = Canvas(recorder, Rect.fromLTWH(0, 0, width, height));

      // 白色背景
      canvas.drawRect(
        Rect.fromLTWH(0, 0, width, height),
        Paint()..color = Colors.white,
      );

      // 绘制签名
      final paint = Paint()
        ..color = Colors.black
        ..strokeWidth = 3.0
        ..strokeCap = StrokeCap.round
        ..strokeJoin = StrokeJoin.round
        ..style = PaintingStyle.stroke;

      // 计算缩放比例
      final renderBox = context.findRenderObject() as RenderBox?;
      if (renderBox == null) return null;

      final size = renderBox.size;
      final scaleX = width / size.width;
      final scaleY = height / size.height;

      for (final stroke in _strokes) {
        if (stroke.length > 1) {
          final path = Path();
          path.moveTo(stroke[0].dx * scaleX, stroke[0].dy * scaleY);
          for (var i = 1; i < stroke.length; i++) {
            path.lineTo(stroke[i].dx * scaleX, stroke[i].dy * scaleY);
          }
          canvas.drawPath(path, paint);
        }
      }

      final picture = recorder.endRecording();
      final img = await picture.toImage(width.toInt(), height.toInt());
      final byteData = await img.toByteData(format: ui.ImageByteFormat.png);

      return byteData?.buffer.asUint8List();
    } catch (e) {
      debugPrint('渲染签名图片失败: $e');
      return null;
    }
  }

  /// 处理笔画开始
  void _onPanStart(DragStartDetails details) {
    final now = DateTime.now().millisecondsSinceEpoch;

    // 记录签名开始时间
    _signatureStartTime ??= now;

    // 记录笔画开始时间
    _currentStrokeStartTime = now;

    setState(() {
      _currentStroke = [details.localPosition];
      _currentTracePoints = [
        SignaturePoint(
          x: details.localPosition.dx,
          y: details.localPosition.dy,
          timestamp: now,
        ),
      ];
    });
  }

  /// 处理笔画更新
  void _onPanUpdate(DragUpdateDetails details) {
    final now = DateTime.now().millisecondsSinceEpoch;

    setState(() {
      _currentStroke.add(details.localPosition);
      _currentTracePoints.add(
        SignaturePoint(
          x: details.localPosition.dx,
          y: details.localPosition.dy,
          timestamp: now,
        ),
      );
    });
  }

  /// 处理笔画结束
  void _onPanEnd(DragEndDetails details) {
    final now = DateTime.now().millisecondsSinceEpoch;

    setState(() {
      if (_currentStroke.isNotEmpty) {
        _strokes.add(List.from(_currentStroke));
        _currentStroke.clear();

        // 保存轨迹数据
        if (_currentTracePoints.isNotEmpty && _currentStrokeStartTime != null) {
          _traceStrokes.add(
            SignatureStroke(
              points: List.from(_currentTracePoints),
              startTime: _currentStrokeStartTime!,
              endTime: now,
            ),
          );
        }
        _currentTracePoints.clear();
        _currentStrokeStartTime = null;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xFFFFF7E6),
      child: Row(
        children: [
          // 左侧操作区
          Container(
            width: 100,
            padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 8),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                // 取消按钮
                GestureDetector(
                  onTap: widget.onCancel,
                  child: Container(
                    width: 80,
                    height: 48,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(
                        color: const Color(0xFFD4AF37),
                        width: 1,
                      ),
                    ),
                    child: const Center(
                      child: Text(
                        '取消',
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          color: Color(0xFFD4AF37),
                        ),
                      ),
                    ),
                  ),
                ),
                // 清除按钮
                GestureDetector(
                  onTap: _clear,
                  child: Container(
                    width: 80,
                    height: 48,
                    decoration: BoxDecoration(
                      color: const Color(0xFFFFEBEE),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.refresh,
                          color: Color(0xFFE53935),
                          size: 18,
                        ),
                        SizedBox(width: 4),
                        Text(
                          '清除',
                          style: TextStyle(
                            fontSize: 14,
                            color: Color(0xFFE53935),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          // 中间签名区域
          Expanded(
            child: Column(
              children: [
                // 顶部提示和姓名显示
                Container(
                  padding: const EdgeInsets.symmetric(vertical: 8),
                  child: Column(
                    children: [
                      // 主提示文字
                      const Text(
                        '请使用正楷书写您的真实姓名',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: Color(0xFFE53935),
                        ),
                      ),
                      const SizedBox(height: 4),
                      // 显示用户姓名供参照
                      if (widget.userName != null && widget.userName!.isNotEmpty)
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            const Text(
                              '请签署：',
                              style: TextStyle(
                                fontSize: 14,
                                color: Color(0xFF666666),
                              ),
                            ),
                            Text(
                              widget.userName!,
                              style: const TextStyle(
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                                color: Color(0xFF5D4037),
                              ),
                            ),
                          ],
                        ),
                    ],
                  ),
                ),
                // 签名区域
                Expanded(
                  child: Container(
                    margin: const EdgeInsets.fromLTRB(0, 0, 0, 8),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(
                        color: const Color(0xFFD4AF37),
                        width: 2,
                      ),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withValues(alpha: 0.1),
                          blurRadius: 10,
                          offset: const Offset(0, 4),
                        ),
                      ],
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(10),
                      child: GestureDetector(
                        onPanStart: _onPanStart,
                        onPanUpdate: _onPanUpdate,
                        onPanEnd: _onPanEnd,
                        child: CustomPaint(
                          painter: _SignaturePainter(
                            strokes: _strokes,
                            currentStroke: _currentStroke,
                          ),
                          child: Container(),
                        ),
                      ),
                    ),
                  ),
                ),
                // 底部状态提示
                Container(
                  padding: const EdgeInsets.only(bottom: 8),
                  child: Text(
                    _hasSignature ? '已签名，点击右侧确认提交' : '在白色区域内签名',
                    style: TextStyle(
                      fontSize: 12,
                      color: _hasSignature
                          ? const Color(0xFF4CAF50)
                          : const Color(0xFF999999),
                    ),
                  ),
                ),
              ],
            ),
          ),
          // 右侧确认按钮
          Container(
            width: 100,
            padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 8),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                GestureDetector(
                  onTap: _submit,
                  child: Container(
                    width: 80,
                    height: 80,
                    decoration: BoxDecoration(
                      color: _hasSignature
                          ? const Color(0xFFD4AF37)
                          : const Color(0xFFD4AF37).withValues(alpha: 0.5),
                      borderRadius: BorderRadius.circular(40),
                      boxShadow: _hasSignature
                          ? [
                              BoxShadow(
                                color:
                                    const Color(0xFFD4AF37).withValues(alpha: 0.3),
                                blurRadius: 15,
                                offset: const Offset(0, 8),
                              ),
                            ]
                          : null,
                    ),
                    child: const Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.check,
                          color: Colors.white,
                          size: 32,
                        ),
                        Text(
                          '确认',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

/// 签名绘制器
class _SignaturePainter extends CustomPainter {
  final List<List<Offset>> strokes;
  final List<Offset> currentStroke;

  _SignaturePainter({
    required this.strokes,
    required this.currentStroke,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.black
      ..strokeWidth = 3.0
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..style = PaintingStyle.stroke;

    // 绘制已完成的笔画
    for (final stroke in strokes) {
      if (stroke.length > 1) {
        final path = Path();
        path.moveTo(stroke[0].dx, stroke[0].dy);
        for (var i = 1; i < stroke.length; i++) {
          path.lineTo(stroke[i].dx, stroke[i].dy);
        }
        canvas.drawPath(path, paint);
      }
    }

    // 绘制当前笔画
    if (currentStroke.length > 1) {
      final path = Path();
      path.moveTo(currentStroke[0].dx, currentStroke[0].dy);
      for (var i = 1; i < currentStroke.length; i++) {
        path.lineTo(currentStroke[i].dx, currentStroke[i].dy);
      }
      canvas.drawPath(path, paint);
    }

    // 绘制提示文字（如果没有签名）
    if (strokes.isEmpty && currentStroke.isEmpty) {
      final textPainter = TextPainter(
        text: const TextSpan(
          text: '请在此处签名',
          style: TextStyle(
            color: Color(0xFFCCCCCC),
            fontSize: 24,
          ),
        ),
        textDirection: TextDirection.ltr,
      );
      textPainter.layout();
      textPainter.paint(
        canvas,
        Offset(
          (size.width - textPainter.width) / 2,
          (size.height - textPainter.height) / 2,
        ),
      );
    }
  }

  @override
  bool shouldRepaint(covariant _SignaturePainter oldDelegate) {
    return true;
  }
}
