import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_esc_pos_network/flutter_esc_pos_network.dart';
import 'package:enaklo_pos/core/extensions/string_ext.dart';
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
import 'package:enaklo_pos/data/datasources/product_local_datasource.dart';
import 'package:intl/intl.dart';
import 'package:print_bluetooth_thermal/print_bluetooth_thermal.dart';

import 'package:enaklo_pos/core/extensions/build_context_ext.dart';
import 'package:enaklo_pos/core/extensions/int_ext.dart';
import 'package:enaklo_pos/data/dataoutputs/print_dataoutputs.dart';
import 'package:enaklo_pos/data/models/response/table_model.dart';
import 'package:enaklo_pos/presentation/home/models/product_quantity.dart';

import '../../../core/assets/assets.gen.dart';
import '../../../core/components/buttons.dart';
import '../../../core/components/spaces.dart';
import '../../table/blocs/get_table/get_table_bloc.dart';
import '../bloc/checkout/checkout_bloc.dart';
import '../bloc/order/order_bloc.dart';
import '../models/order_type.dart';
import 'package:enaklo_pos/core/utils/printer_service.dart';

class SaveOrderDialog extends StatefulWidget {
  const SaveOrderDialog({
    super.key,
    required this.data,
    required this.totalQty,
    required this.totalPrice,
    required this.totalTax,
    required this.totalDiscount,
    required this.subTotal,
    required this.normalPrice,
    required this.table,
    required this.draftName,
  });
  final List<ProductQuantity> data;
  final int totalQty;
  final int totalPrice;
  final int totalTax;
  final int totalDiscount;
  final int subTotal;
  final int normalPrice;
  final TableModel table;
  final String draftName;

  @override
  State<SaveOrderDialog> createState() => _SaveOrderDialogState();
}

class _SaveOrderDialogState extends State<SaveOrderDialog> {
  // List<ProductQuantity> data = [];
  // int totalQty = 0;
  // int totalPrice = 0;
  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      content: SingleChildScrollView(
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Center(child: Assets.icons.success.svg()),
            const SpaceHeight(16.0),
            const Center(
              child: Text(
                'Order Berhasil Disimpan',
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 20,
                ),
              ),
            ),
            const SpaceHeight(20.0),
            Row(
              children: [
                Flexible(
                  child: Button.outlined(
                    onPressed: () {
                      context
                          .read<CheckoutBloc>()
                          .add(const CheckoutEvent.started());
                      context
                          .read<GetTableBloc>()
                          .add(const GetTableEvent.getTables());
                      context.popToRoot();
                    },
                    label: 'Kembali',
                  ),
                ),
                const SpaceWidth(8.0),
                Flexible(
                  child: BlocBuilder<CheckoutBloc, CheckoutState>(
                    builder: (context, state) {
                      final orderType = state.maybeWhen(
                        orElse: () => OrderType.dineIn,
                        loaded: (items, discountModel, discount, discountAmount, tax, serviceCharge, totalQuantity, totalPrice, draftName, orderType) => orderType,
                      );
                      
                      return Button.filled(
                        onPressed: () async {
                      final checkerPrinter = await ProductLocalDatasource
                          .instance
                          .getPrinterByCode('checker');
                      final kitchenPrinter = await ProductLocalDatasource
                          .instance
                          .getPrinterByCode('kitchen');
                      final barPrinter = await ProductLocalDatasource.instance
                          .getPrinterByCode('bar');
                      
                      log("Checker printer: ${checkerPrinter?.toMap()}");
                      log("Kitchen printer: ${kitchenPrinter?.toMap()}");
                      log("Bar printer: ${barPrinter?.toMap()}");
                      
                      // Checker printer
                      if (checkerPrinter != null) {
                        try {
                          final printValue = await PrintDataoutputs.instance
                              .printChecker(
                                  widget.data,
                                  widget.table.tableName,
                                  widget.draftName,
                                  'kasir',
                                  checkerPrinter.paper.toIntegerFromText,
                                  orderType.value);
                          
                          await PrinterService().printWithPrinter(
                            checkerPrinter, 
                            printValue, 
                            context
                          );
                        } catch (e) {
                          log("Error printing checker: $e");
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text('Error printing checker: $e')),
                          );
                        }
                      }

                      // Kitchen printer
                      if (kitchenPrinter != null) {
                        try {
                          final printValue = await PrintDataoutputs.instance.printKitchen(
                            widget.data,
                            widget.table.tableName,
                            widget.draftName,
                            'kasir',
                            kitchenPrinter.paper.toIntegerFromText,
                            orderType.value,
                          );
                          
                          await PrinterService().printWithPrinter(
                            kitchenPrinter, 
                            printValue, 
                            context
                          );
                        } catch (e) {
                          log("Error printing kitchen order: $e");
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text('Error printing kitchen order: $e')),
                          );
                        }
                      }

                      // Bar printer
                      if (barPrinter != null) {
                        try {
                          final printValue = await PrintDataoutputs.instance.printBar(
                            widget.data,
                            widget.table.tableName,
                            widget.draftName,
                            'kasir',
                            barPrinter.paper.toIntegerFromText,
                            orderType.value,
                          );
                          
                          await PrinterService().printWithPrinter(
                            barPrinter, 
                            printValue, 
                            context
                          );
                        } catch (e) {
                          log("Error printing bar order: $e");
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text('Error printing bar order: $e')),
                          );
                        }
                      }
                        },
                        label: 'Print Checker',
                      );
                    },
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
