import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:drago_pos_printer/drago_pos_printer.dart';
import 'package:flutter_svg/svg.dart';
import 'package:max_print_plus/widget/my_button.dart';
// import 'package:webcontent_converter/demo.dart';
// import 'package:webcontent_converter/webcontent_converter.dart';
import '../service/service.dart';

class BluetoothPrinterScreen extends StatefulWidget {
  List<int> bytes;
  EscGenerator generator;
  Function(bool)? onSuccess;
  bool? hideOption;
  BluetoothPrinterScreen({
    super.key,
    required this.bytes,
    required this.generator,
    this.onSuccess,
    this.hideOption = true,
  });

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

class _BluetoothPrinterScreenState extends State<BluetoothPrinterScreen> {
  bool _isLoading = false;
  List<BluetoothPrinter> _printers = [];
  BluetoothPrinterManager? _manager;

  int paperWidth = 0;
  int charPerLine = 0;

  List<String> paperTypes = [];
  bool showCustom = false;
  @override
  void initState() {
    _scan();
    paperWidth = PaperSizeWidth.mm80;
    charPerLine = PaperSizeMaxPerLine.mm80;

    paperTypes.add('58mm');
    paperTypes.add('80mmOld');
    paperTypes.add('80mm');
    paperTypes.add('Custom');

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFFAFAFA),
      body: ListView(
        padding: const EdgeInsets.all(20),
        children: [
          if (!widget.hideOption!)
            DropdownButtonHideUnderline(
              child: DropdownButtonFormField(
                decoration: const InputDecoration(labelText: 'Paper Size'),
                items: paperTypes.map((item) {
                  return DropdownMenuItem(
                    value: item,
                    child: Text(item),
                  );
                }).toList(),
                onChanged: (String? selected) async {
                  showCustom = false;
                  if (selected != null) {
                    if (selected == "58mm") {
                      paperWidth = PaperSizeWidth.mm58;
                      charPerLine = PaperSizeMaxPerLine.mm58;
                    } else if (selected == "80mmOld") {
                      paperWidth = PaperSizeWidth.mm80_Old;
                      charPerLine = PaperSizeMaxPerLine.mm80_Old;
                    } else if (selected == "80mm") {
                      paperWidth = PaperSizeWidth.mm80;
                      charPerLine = PaperSizeMaxPerLine.mm80;
                    } else if (selected == "Custom") {
                      paperWidth = PaperSizeWidth.mm80;
                      charPerLine = PaperSizeMaxPerLine.mm80;
                      showCustom = true;
                    }
                    setState(() {});
                  }
                },
              ),
            ),
          if (showCustom)
            Row(
              children: [
                Expanded(
                    child: TextFormField(
                  initialValue: paperWidth.toString(),
                  onChanged: (val) {
                    if (val.isNotEmpty) {
                      paperWidth = int.parse(val);
                    } else {
                      paperWidth = 0;
                    }
                  },
                )),
                const SizedBox(width: 20),
                Expanded(
                    child: TextFormField(
                  initialValue: charPerLine.toString(),
                  onChanged: (val) {
                    if (val.isNotEmpty) {
                      charPerLine = int.parse(val);
                    } else {
                      charPerLine = 0;
                    }
                  },
                ))
              ],
            ),
          if (!widget.hideOption!) const SizedBox(height: 10),
          if (_printers.isEmpty)
            Container(
              padding: const EdgeInsets.only(top: 100),
              child: Column(
                children: [
                  SvgPicture.asset(
                    'assets/image/ic_printer_bulk.svg',
                    width: 200,
                    height: 200,
                    package: 'max_print_plus',
                    color: const Color.fromARGB(255, 207, 216, 220),
                  ),
                  const SizedBox(
                    height: 16,
                  ),
                  const Text(
                    'Bluetooth Kosong',
                    style: TextStyle(
                      fontWeight: FontWeight.w600,
                      fontSize: 20,
                      color: Color.fromARGB(255, 186, 197, 202),
                    ),
                  )
                ],
              ),
            ),
          ..._printers
              .map((printer) => ListTile(
                    title: Text(
                      "${printer.name}",
                      style: const TextStyle(
                          color: Colors.black,
                          fontWeight: FontWeight.w600,
                          fontSize: 15),
                    ),
                    selectedColor: Colors.green,
                    subtitle: Text("${printer.address}",
                        style: const TextStyle(color: Colors.black)),
                    leading: SvgPicture.asset(
                      'assets/image/ic_bluetooth.svg',
                      width: 30,
                      height: 30,
                      package: 'max_print_plus',
                      color: printer.connected ? Colors.green : Colors.grey,
                    ),
                    onTap: () => _connect(printer),
                    trailing: printer.connected
                        ? Wrap(
                            children: [
                              IconButton(
                                tooltip: 'ESC POS Command',
                                onPressed: () => _startPrinter(1, printer),
                                icon: SvgPicture.asset(
                                  'assets/image/ic_printer_bold.svg',
                                  width: 28,
                                  height: 28,
                                  package: 'max_print_plus',
                                  color: printer.connected
                                      ? Colors.green
                                      : Colors.grey,
                                ),
                              ),
                              // IconButton(
                              //     tooltip: 'Html Print',
                              //     onPressed: () => _startPrinter(3, printer),
                              //     icon: const Icon(Icons.image)),
                            ],
                          )
                        : null,
                    selected: printer.connected,
                  ))
              .toList(),
        ],
      ),
      bottomNavigationBar: Container(
        padding: const EdgeInsets.all(16),
        child: MyButton(
          text: 'Refresh',
          textColor: Colors.black,
          press: _isLoading ? null : _scan,
          width: double.infinity,
        ),
      ),
    );
  }

  _scan() async {
    print("scan");
    setState(() {
      _isLoading = true;
      _printers = [];
    });
    var printers = await BluetoothPrinterManager.discover();
    print(printers);
    setState(() {
      _isLoading = false;
      _printers = printers;
    });
  }

  Future _connect(BluetoothPrinter printer) async {
    var manager = BluetoothPrinterManager(printer);
    // await manager.connect();
    print(" -==== connected =====- ");
    setState(() {
      _manager = manager;
      printer.connected = true;
    });
  }

  _startPrinter(int byteType, BluetoothPrinter printer) async {
    var profile = await CapabilityProfile.load();
    await _connect(printer);

    // late List<int> data;
    // if (byteType == 1) {
    List<int> data = await ESCPrinterService(null).getSamplePosBytes(
      paperSizeWidthMM: paperWidth,
      maxPerLine: charPerLine,
      profile: profile,
      bytesData: widget.bytes,
    );

    if (_manager != null) {
      if (!await _manager!.checkConnected()) await _manager!.connect();
      _manager!.writeBytes(data, isDisconnect: true);
    }

    // widget.onSuccess!(true);
    Navigator.pop(context, true);
  }
}
