import 'dart:developer';
import 'dart:io';

import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/widgets.dart';

class HelperPdfService {
  static Future<File> saveDocument({
    required String name,
    required Document pdf,
  }) async {
    try {
      log("Starting PDF save process for: $name");
      log("PDF document object: $pdf");

      final bytes = await pdf.save();
      log("PDF bytes generated successfully, size: ${bytes.length} bytes");

      if (bytes.isEmpty) {
        log("WARNING: PDF bytes are empty!");
        return Future.error("PDF bytes are empty");
      }

      final dir = await getApplicationDocumentsDirectory();
      log("Documents directory: ${dir.path}");

      final file = File('${dir.path}/$name');
      log("Saving PDF to: ${file.path}");

      await file.writeAsBytes(bytes);
      log("PDF saved successfully to: ${file.path}");

      // Verify file was created
      if (await file.exists()) {
        final fileSize = await file.length();
        log("File exists and size is: $fileSize bytes");
      } else {
        log("ERROR: File was not created!");
        return Future.error("File was not created");
      }

      return file;
    } catch (e) {
      log("Failed to save document: $e");
      log("Error stack trace: ${StackTrace.current}");
      return Future.error("Failed to save document: $e");
    }
  }

  static Future openFile(File file) async {
    try {
      final url = file.path;
      log("Attempting to open file: $url");

      if (!await file.exists()) {
        log("ERROR: File does not exist: $url");
        return;
      }

      final fileSize = await file.length();
      log("File exists and size is: $fileSize bytes");

      log("Calling OpenFile.open...");
      final result = await OpenFile.open(url, type: "application/pdf");
      log("OpenFile result: $result");

      if (result.type == ResultType.done) {
        log("File opened successfully");
      } else {
        log("File opening failed with result: ${result.type}");
        log("Error message: ${result.message}");
      }
    } catch (e) {
      log("Failed to open file: $e");
      log("Error stack trace: ${StackTrace.current}");
    }
  }
}
