import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:io';
import 'package:flutter/services.dart';

/// Konfigurasi global untuk printing
class PrintConfig {
  static const String PAPER_SIZE_MM58 = '58mm';
  static const String PAPER_SIZE_MM80 = '80mm';

  // Default settings
  static const String DEFAULT_PAPER_SIZE = PAPER_SIZE_MM58;
  static const int DEFAULT_LOGO_WIDTH = 300;
  static const int MAX_LINE_LENGTH = 32;
  static const int DEFAULT_FEED_LINES = 2;

  // Shared preferences keys
  static const String PREF_PAPER_SIZE = 'printer_paper_size';
  static const String PREF_LOGO_WIDTH = 'printer_logo_width';
  static const String PREF_MAX_LINE_LENGTH = 'printer_max_line_length';

  /// Load printer configuration from shared preferences
  static Future<Map<String, dynamic>> loadPrinterConfig() async {
    final prefs = await SharedPreferences.getInstance();

    return {
      'paperSize': prefs.getString(PREF_PAPER_SIZE) ?? DEFAULT_PAPER_SIZE,
      'logoWidth': prefs.getInt(PREF_LOGO_WIDTH) ?? DEFAULT_LOGO_WIDTH,
      'maxLineLength': prefs.getInt(PREF_MAX_LINE_LENGTH) ?? MAX_LINE_LENGTH,
    };
  }

  /// Save printer configuration to shared preferences
  static Future<void> savePrinterConfig({
    String? paperSize,
    int? logoWidth,
    int? maxLineLength,
  }) async {
    final prefs = await SharedPreferences.getInstance();

    if (paperSize != null) {
      await prefs.setString(PREF_PAPER_SIZE, paperSize);
    }
    if (logoWidth != null) {
      await prefs.setInt(PREF_LOGO_WIDTH, logoWidth);
    }
    if (maxLineLength != null) {
      await prefs.setInt(PREF_MAX_LINE_LENGTH, maxLineLength);
    }
  }

  /// Get paper size enum based on configuration
  static String getPaperSizeEnum(String paperSize) {
    switch (paperSize) {
      case PAPER_SIZE_MM58:
        return 'mm58';
      case PAPER_SIZE_MM80:
        return 'mm80';
      default:
        return 'mm58';
    }
  }
}

/// Error handling utilities for printing
class PrintErrorHandler {
  /// Handle common printing errors
  static String getErrorMessage(Exception e) {
    if (e is SocketException) {
      return 'Koneksi ke printer terputus: ${e.message}';
    } else if (e is PlatformException) {
      return 'Error printer: ${(e).message}';
    } else {
      return 'Gagal mencetak struk: $e';
    }
  }

  /// Log error with context
  static void logPrintError(String context, Exception e,
      [StackTrace? stackTrace]) {
    debugPrint('[$context] Error: $e');
    if (stackTrace != null) {
      debugPrint('[$context] Stack trace: $stackTrace');
    }
  }
}
