import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:sunmi_printer_plus/sunmi_printer_plus.dart';

/// Service for printing to Sunmi thermal printers
class SunmiService {
  /// Print warehouse export form to Sunmi printer
  static Future<void> printWarehouseExport({
    required BuildContext context,
    required String warehouseName,
    required int productId,
    required String productCode,
    required String productName,
    String? stageName,
    required double passedKg,
    required int passedPcs,
    required double issuedKg,
    required int issuedPcs,
    String? responsibleName,
    String? receiverName,
    String? barcodeData,
  }) async {
    try {
      // Check if printer is bound
      final bool? isBound = await SunmiPrinter.bindingPrinter();
      if (isBound != true) {
        throw Exception('Sunmi printer not available');
      }

      // Format current date
      final dt = DateFormat('dd/MM/yyyy HH:mm').format(DateTime.now());

      // Reset printer
      await SunmiPrinter.initPrinter();
      await SunmiPrinter.resetFontSize();

      // Title - PHIẾU XUẤT KHO
      await SunmiPrinter.setAlignment(SunmiPrintAlign.CENTER);
      await SunmiPrinter.bold();
      await SunmiPrinter.setCustomFontSize(30);
      await SunmiPrinter.printText('PHIEU XUAT KHO');
      await SunmiPrinter.resetBold();
      await SunmiPrinter.setCustomFontSize(24);
      await SunmiPrinter.lineWrap(1);

      // Company name
      await SunmiPrinter.printText('Cong ty TNHH Co Khi Chinh Xac Minh Thu');
      await SunmiPrinter.resetFontSize();
      await SunmiPrinter.lineWrap(1);

      // Warehouse name
      await SunmiPrinter.printText(warehouseName);
      await SunmiPrinter.lineWrap(1);

      // Date
      await SunmiPrinter.printText('Ngay: $dt');
      await SunmiPrinter.lineWrap(2);

      // Separator line
      await SunmiPrinter.line();
      await SunmiPrinter.lineWrap(1);

      // Product information
      await SunmiPrinter.setAlignment(SunmiPrintAlign.LEFT);
      await SunmiPrinter.bold();
      await SunmiPrinter.printText('THONG TIN SAN PHAM');
      await SunmiPrinter.resetBold();
      await SunmiPrinter.lineWrap(1);

      // ProductId
      await SunmiPrinter.printText('ProductId: $productId');
      await SunmiPrinter.lineWrap(1);

      // Product Code
      await SunmiPrinter.printText('Ma san pham: $productCode');
      await SunmiPrinter.lineWrap(1);

      // Product Name
      await SunmiPrinter.printText('Ten san pham: $productName');
      await SunmiPrinter.lineWrap(1);

      // Stage Name
      await SunmiPrinter.printText('Cong doan: ${stageName ?? '-'}');
      await SunmiPrinter.lineWrap(2);

      // Separator line
      await SunmiPrinter.line();
      await SunmiPrinter.lineWrap(1);

      // Quantities
      await SunmiPrinter.bold();
      await SunmiPrinter.printText('SO LUONG');
      await SunmiPrinter.resetBold();
      await SunmiPrinter.lineWrap(1);

      // Table header
      await SunmiPrinter.setAlignment(SunmiPrintAlign.LEFT);
      await SunmiPrinter.printText('Loai          KG         PCS');
      await SunmiPrinter.line();

      // Passed quantity (Hàng đạt)
      final passedLine = 'Hang dat      ${passedKg.toStringAsFixed(2).padLeft(7)}     ${passedPcs.toString().padLeft(5)}';
      await SunmiPrinter.printText(passedLine);

      // Issued quantity (Hàng lỗi)
      final issuedLine = 'Hang loi      ${issuedKg.toStringAsFixed(2).padLeft(7)}     ${issuedPcs.toString().padLeft(5)}';
      await SunmiPrinter.printText(issuedLine);
      await SunmiPrinter.lineWrap(2);

      // Separator line
      await SunmiPrinter.line();
      await SunmiPrinter.lineWrap(1);

      // Responsible person
      await SunmiPrinter.printText('Nhan vien kho: ${responsibleName ?? '-'}');
      await SunmiPrinter.lineWrap(1);

      // Receiver
      await SunmiPrinter.printText('Nhan vien tiep nhan: ${receiverName ?? '-'}');
      await SunmiPrinter.lineWrap(2);

      // Barcode
      if (barcodeData != null && barcodeData.isNotEmpty) {
        await SunmiPrinter.line();
        await SunmiPrinter.setAlignment(SunmiPrintAlign.CENTER);
        await SunmiPrinter.printBarCode(barcodeData);
        await SunmiPrinter.lineWrap(2);
      }

      // Footer
      await SunmiPrinter.line();
      await SunmiPrinter.setAlignment(SunmiPrintAlign.CENTER);
      await SunmiPrinter.printText('Nguoi nhan');
      await SunmiPrinter.lineWrap(4);

      // Cut paper
      await SunmiPrinter.cut();

      // Show success message
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Đã in thành công!'),
            backgroundColor: Colors.green,
            duration: Duration(seconds: 2),
          ),
        );
      }
    } catch (e) {
      // Show error message
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Lỗi khi in: ${e.toString()}'),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 3),
          ),
        );
      }
      rethrow;
    }
  }
}
