import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_editor_sdk/photo_editor_sdk.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:imgly_sdk/imgly_sdk.dart'; // Import the imgly_sdk package

class ImageEditorScreen extends StatefulWidget {
  final Uint8List image;

  const ImageEditorScreen({Key? key, required this.image}) : super(key: key);

  @override
  ImageEditorScreenState createState() => ImageEditorScreenState();
}

class ImageEditorScreenState extends State<ImageEditorScreen> {
  late File imageFile;

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

  Future<void> _saveImageToFile() async {
    final tempDir = await getTemporaryDirectory();
    final file = File('${tempDir.path}/temp_image.png');
    await file.writeAsBytes(widget.image);
    setState(() {
      imageFile = file;
    });
  }

  Future<void> _saveImageToGallery(String imagePath) async {
    try {
      final result = await ImageGallerySaver.saveFile(imagePath);
      if (result['isSuccess']) {
        _showSnackBar('Image saved to gallery successfully!');
      } else {
        throw Exception('Failed to save image to gallery.');
      }
    } catch (e) {
      _showSnackBar('Failed to save image to gallery: ${e.toString()}');
    }
  }

  void _showSnackBar(String message) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }

  Future<void> _openPhotoEditor() async {
    try {
      final result = await PESDK.openEditor(
        image: imageFile.path,
        configuration: Configuration(
          tools: [
            Tool.adjustment,
            Tool.brush,
            Tool.filter,
            Tool.focus,
            Tool.frame,
            Tool.overlay,
            Tool.sticker,
            Tool.text,
            Tool.textDesign,
            Tool.transform,
            Tool.trim,
            Tool.watermark,
          ],
          enableZoom: true,
          forceCrop: false,
          singleToolMode: false,
          toolbarMode: ToolbarMode.bottom,
        ),
      );

      if (result != null && mounted) {
        if (result.hasChanges) {
          final editedImagePath = result.image;

          // Save the edited image to the gallery
          await _saveImageToGallery(editedImagePath);

          // Read the edited image bytes
          final editedFile = File(editedImagePath);
          final editedBytes = await editedFile.readAsBytes();

          // Return the edited image bytes to the previous screen
          Navigator.of(context).pop(editedBytes);
        } else {
          _showSnackBar('No changes were made to the image.');
        }
      }
    } catch (e) {
      _showSnackBar('Failed to edit image: ${e.toString()}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Image Editor'),
        leading: IconButton(
          icon: const Icon(Icons.close),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.check),
            onPressed: _openPhotoEditor,
          ),
        ],
      ),
      body: Center(
        child: imageFile.existsSync()
            ? Image.file(imageFile)
            : const CircularProgressIndicator(),
      ),
    );
  }
}

class Configuration {
  final List<EditorTool> tools;
  final bool enableZoom;
  final bool forceCrop;
  final bool singleToolMode;
  final ToolbarMode toolbarMode;

  Configuration({
    this.tools = const [
      EditorTool.adjustment,
      EditorTool.brush,
      EditorTool.filter,
      EditorTool.focus,
      EditorTool.frame,
      EditorTool.overlay,
      EditorTool.sticker,
      EditorTool.text,
      EditorTool.textDesign,
      EditorTool.transform,
      EditorTool.trim,
      EditorTool.watermark,
    ],
    this.enableZoom = true,
    this.forceCrop = false,
    this.singleToolMode = false,
    this.toolbarMode = ToolbarMode.bottom,
  });

  Map<String, dynamic> toJson() {
    return {
      'tools': tools.map((tool) => tool.toString()).toList(),
      'enableZoom': enableZoom,
      'forceCrop': forceCrop,
      'singleToolMode': singleToolMode,
      'toolbarMode': toolbarMode.toString(),
    };
  }
}

class EditorTool {
  static const adjustment = EditorTool._('adjustment');
  static const brush = EditorTool._('brush');
  static const filter = EditorTool._('filter');
  static const focus = EditorTool._('focus');
  static const frame = EditorTool._('frame');
  static const overlay = EditorTool._('overlay');
  static const sticker = EditorTool._('sticker');
  static const text = EditorTool._('text');
  static const textDesign = EditorTool._('textDesign');
  static const transform = EditorTool._('transform');
  static const trim = EditorTool._('trim');
  static const watermark = EditorTool._('watermark');

  final String name;

  const EditorTool._(this.name);

  @override
  String toString() => name;
}

enum ToolbarMode { bottom, top }