import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:ui' as ui;

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_drawing_board/flutter_drawing_board.dart';
import 'package:flutter_drawing_board/paint_contents.dart';
import 'package:flutter_drawing_board/paint_extension.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:unit2/utils/request_permission.dart';
import 'package:http/http.dart';
import 'package:unit2/utils/urls.dart'; // Removed 'as http'

// import 'test_data.dart';

Future<ui.Image> _getImage(String path) async {
  final Completer<ImageInfo> completer = Completer<ImageInfo>();
  final NetworkImage img = NetworkImage(path);
  img.resolve(ImageConfiguration.empty).addListener(
    ImageStreamListener((ImageInfo info, _) {
      completer.complete(info);
    }),
  );

  final ImageInfo imageInfo = await completer.future;

  return imageInfo.image;
}

const Map<String, dynamic> _testLine1 = <String, dynamic>{
  'type': 'StraightLine',
  'startPoint': <String, dynamic>{
    'dx': 68.94337550070736,
    'dy': 62.05980083656557
  },
  'endPoint': <String, dynamic>{
    'dx': 277.1373386828114,
    'dy': 277.32029957032194
  },
  'paint': <String, dynamic>{
    'blendMode': 3,
    'color': 4294198070,
    'filterQuality': 3,
    'invertColors': false,
    'isAntiAlias': false,
    'strokeCap': 1,
    'strokeJoin': 1,
    'strokeWidth': 4.0,
    'style': 1
  }
};

const Map<String, dynamic> _testLine2 = <String, dynamic>{
  'type': 'StraightLine',
  'startPoint': <String, dynamic>{
    'dx': 106.35164817830423,
    'dy': 255.9575653134524
  },
  'endPoint': <String, dynamic>{
    'dx': 292.76034659254094,
    'dy': 92.125586665872
  },
  'paint': <String, dynamic>{
    'blendMode': 3,
    'color': 4294198070,
    'filterQuality': 3,
    'invertColors': false,
    'isAntiAlias': false,
    'strokeCap': 1,
    'strokeJoin': 1,
    'strokeWidth': 4.0,
    'style': 1
  }
};

/// Custom drawn triangles
class Triangle extends PaintContent {
  Triangle();

  Triangle.data({
    required this.startPoint,
    required this.A,
    required this.B,
    required this.C,
    required Paint paint,
  }) : super.paint(paint);

  factory Triangle.fromJson(Map<String, dynamic> data) {
    return Triangle.data(
      startPoint: jsonToOffset(data['startPoint'] as Map<String, dynamic>),
      A: jsonToOffset(data['A'] as Map<String, dynamic>),
      B: jsonToOffset(data['B'] as Map<String, dynamic>),
      C: jsonToOffset(data['C'] as Map<String, dynamic>),
      paint: jsonToPaint(data['paint'] as Map<String, dynamic>),
    );
  }

  Offset startPoint = Offset.zero;

  Offset A = Offset.zero;
  Offset B = Offset.zero;
  Offset C = Offset.zero;

  @override
  void startDraw(Offset startPoint) => this.startPoint = startPoint;

  @override
  void drawing(Offset nowPoint) {
    A = Offset(
        startPoint.dx + (nowPoint.dx - startPoint.dx) / 2, startPoint.dy);
    B = Offset(startPoint.dx, nowPoint.dy);
    C = nowPoint;
  }

  @override
  void draw(Canvas canvas, Size size, bool deeper) {
    final Path path = Path()
      ..moveTo(A.dx, A.dy)
      ..lineTo(B.dx, B.dy)
      ..lineTo(C.dx, C.dy)
      ..close();

    canvas.drawPath(path, paint);
  }

  @override
  Triangle copy() => Triangle();

  @override
  Map<String, dynamic> toContentJson() {
    return <String, dynamic>{
      'startPoint': startPoint.toJson(),
      'A': A.toJson(),
      'B': B.toJson(),
      'C': C.toJson(),
      'paint': paint.toJson(),
    };
  }
}

/// Custom drawn image
/// url: https://web-strapi.mrmilu.com/uploads/flutter_logo_470e9f7491.png
const String _imageUrl =
    'https://web-strapi.mrmilu.com/uploads/flutter_logo_470e9f7491.png';

class ImageContent extends PaintContent {
  ImageContent(this.image, {this.imageUrl = ''});

  ImageContent.data({
    required this.startPoint,
    required this.size,
    required this.image,
    required this.imageUrl,
    required Paint paint,
  }) : super.paint(paint);

  factory ImageContent.fromJson(Map<String, dynamic> data) {
    return ImageContent.data(
      startPoint: jsonToOffset(data['startPoint'] as Map<String, dynamic>),
      size: jsonToOffset(data['size'] as Map<String, dynamic>),
      imageUrl: data['imageUrl'] as String,
      image: data['image'] as ui.Image,
      paint: jsonToPaint(data['paint'] as Map<String, dynamic>),
    );
  }

  Offset startPoint = Offset.zero;
  Offset size = Offset.zero;
  final String imageUrl;
  final ui.Image image;

  @override
  void startDraw(Offset startPoint) => this.startPoint = startPoint;

  @override
  void drawing(Offset nowPoint) => size = nowPoint - startPoint;

  @override
  void draw(Canvas canvas, Size size, bool deeper) {
    final Rect rect = Rect.fromPoints(startPoint, startPoint + this.size);
    paintImage(canvas: canvas, rect: rect, image: image, fit: BoxFit.fill);
  }

  @override
  ImageContent copy() => ImageContent(image);

  @override
  Map<String, dynamic> toContentJson() {
    return <String, dynamic>{
      'startPoint': startPoint.toJson(),
      'size': size.toJson(),
      'imageUrl': imageUrl,
      'paint': paint.toJson(),
    };
  }
}

class DrawingScreen extends StatelessWidget {
  const DrawingScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Drawing Test',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  /// 绘制控制器
  final DrawingController _drawingController = DrawingController();

  final TransformationController _transformationController =
      TransformationController();

  final GlobalKey _repaintBoundaryKey = GlobalKey();

  File? _image;

  final String imagePath = '/data/user/0/com.app.rpass/cache/182.png';

  @override
  void dispose() {
    _drawingController.dispose();
    super.dispose();
  }

  /// 获取画板数据 `getImageData()`
  Future<void> _getImageData() async {
    final Uint8List? data =
        (await _drawingController.getImageData())?.buffer.asUint8List();
    if (data == null) {
      debugPrint('获取图片数据失败');
      return;
    }

    if (mounted) {
      showDialog<void>(
        context: context,
        builder: (BuildContext c) {
          return Material(
            color: Colors.transparent,
            child: InkWell(
                onTap: () => Navigator.pop(c), child: Image.memory(data)),
          );
        },
      );
    }
  }

  Future<String> _saveImageToDevice(Uint8List data) async {
    // Get the temporary directory
    final directory = await getTemporaryDirectory();
    final tempDirectory = directory.path;

    // Create a file path in the temporary directory
    final filePath = '$tempDirectory/181.png';
    final file = File(filePath);

    // Write the image bytes to the file
    await file.writeAsBytes(data);

    // Return the file path
    print(filePath);
    return filePath;
  }

  Future<void> _saveAndShowImage() async {
    final Uint8List? data =
        (await _drawingController.getImageData())?.buffer.asUint8List();
    if (data == null) {
      debugPrint('Failed to get image data');
      return;
    }

    final path = await _saveImageToDevice(data);

    if (mounted) {
      showDialog<void>(
        context: context,
        builder: (BuildContext c) {
          return Material(
            color: Colors.transparent,
            child: InkWell(
                onTap: () => Navigator.pop(c), child: Image.memory(data)),
          );
        },
      );
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Image saved to $path')),
      );
    }
  }

  Future<void> _showImage() async {
    showDialog<void>(
      context: context,
      builder: (BuildContext c) {
        return Material(
          color: Colors.transparent,
          child: InkWell(
              onTap: () => Navigator.pop(c),
              child:
                  Image.file(File('/data/user/0/com.app.rpass/cache/img.png'))),
        );
      },
    );
  }

  void _restBoard() {
    _transformationController.value = Matrix4.identity();
  }

  Future<Response> _postBuildingDetails(Map<String, dynamic> details) async {
    String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z";
    String xClientKeySecret = "unitcYqAN7GGalyz";

    // Construct the headers for the request
    Map<String, String> headers = {
      'Content-Type': 'multipart/form-data',
      'X-Client-Key': xClientKey,
      'X-Client-Secret': xClientKeySecret,
    };

    // Create a MultipartRequest
    var request = MultipartRequest(
      'POST',
      Uri.parse(
          'https://${Url.instance.host()}/api/rptass_app/bldgappr_sketch/'),
    );

    // Add the headers to the request
    request.headers.addAll(headers);

    // Add JSON data as a field
    // Add individual fields to the request
    details.forEach((key, value) {
      request.fields[key] = value.toString();
    });

    var file = File(imagePath);
    // Add the floor sketch image file, if it exists

    request.files.add(
      await MultipartFile.fromPath(
        'floor_sketch', // Field name in the API
        file.path,
        filename: file.path,
      ),
    );

    // Send the request and get the response
    var streamedResponse = await request.send();
    return await Response.fromStream(streamedResponse);
  }

  Future<void> _uploadImage() async {
    // Create a map with the required fields
    var file = File(imagePath);
    Map<String, dynamic> detailsMap = {
      "bldgappr_details_id": 182, // int8 NOT NULL
      "date_created": DateTime.now().toIso8601String(), // timestamptz NULL
      "floor_sketch": file.path, // text NULL
      "gen_code": "5TH", // varchar(20) NOT NULL
    };

    try {
      Response response = await _postBuildingDetails(detailsMap);
      print(response.body);

      if (response.statusCode == 201) {
        print('Upload successful');
      } else {
        print('Upload failed with status: ${response.statusCode}');
      }
    } catch (e) {
      print('Error: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.white,
      body: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              IconButton(
                icon: const Icon(Icons.delete_rounded),
                color: Colors.red,
                iconSize: 38,
                tooltip: 'Open shopping cart',
                onPressed: () {
                  _showImage();
                },
              ),
              IconButton(
                icon: const Icon(Icons.check_circle),
                color: Colors.red,
                iconSize: 35,
                tooltip: 'Open shopping cart',
                onPressed: () {
                  _saveAndShowImage();
                },
              ),
            ],
          ),
          Expanded(
            child: LayoutBuilder(
              builder: (BuildContext context, BoxConstraints constraints) {
                return RepaintBoundary(
                  key: _repaintBoundaryKey,
                  child: DrawingBoard(
                    // boardPanEnabled: false,
                    // boardScaleEnabled: false,
                    transformationController: _transformationController,
                    controller: _drawingController,
                    background: Container(
                      width: constraints.maxWidth,
                      height: constraints.maxHeight,
                      color: Colors.grey,
                    ),
                    showDefaultActions: true,
                    showDefaultTools: true,

                    defaultToolsBuilder: (Type t, _) {
                      return DrawingBoard.defaultTools(t, _drawingController)
                        ..insert(
                          1,
                          DefToolItem(
                            icon: Icons.change_history_rounded,
                            isActive: t == Triangle,
                            onTap: () =>
                                _drawingController.setPaintContent(Triangle()),
                          ),
                        );
                    },
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
