import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_signaturepad/signaturepad.dart';

class SignImageService {
  Future<Uint8List> getSignPngBytes(SfSignaturePadState state) async {
    final image = await getSignImage(state);
    final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    final bytes = byteData!.buffer.asUint8List();
    return bytes;
  }

  Future<ui.Image> getSignImage(SfSignaturePadState state) async {
    var paths = state.toPathList();
    Rect? bounds;

    for (final path in paths) {
      final pathBounds = path.getBounds();
      if (bounds == null) {
        bounds = pathBounds;
      } else {
        bounds = bounds.expandToInclude(pathBounds);
      }
    }

    if (bounds == null) {
      throw ArgumentError('The paths list is empty!');
    }

    final offset = Offset(-bounds.left, -bounds.top);
    final recorder = ui.PictureRecorder();
    final canvas = Canvas(recorder);
    var scale = 2.0;
    canvas.scale(scale); // Масштабування для більшої деталізації

    final paint = Paint()
      ..color = Colors.black
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1.0
      ..isAntiAlias = true
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round;

    for (final path in paths) {
      canvas.drawPath(path.shift(offset), paint);
    }

    final picture = recorder.endRecording();
    return await picture.toImage(
      (bounds.width * scale).ceil(),
      (bounds.height * scale).ceil(),
    );
  }
}
