import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../../../../application/printer/printer_form/printer_form_bloc.dart';
import '../../../../../../../application/printer/printer_loader/printer_loader_bloc.dart';
import '../../../../../../../common/theme/theme.dart';
import '../../../../../../components/card/error_card.dart';
import '../../../../../../components/loader/loader_with_text.dart';
import '../../../../../../components/toast/flushbar.dart';
import '../../widgets/printer_card.dart';
import 'setting_printer_form.dart';

class SettingPrinterTicket extends StatefulWidget {
  const SettingPrinterTicket({super.key});

  @override
  State<SettingPrinterTicket> createState() => _SettingPrinterTicketState();
}

class _SettingPrinterTicketState extends State<SettingPrinterTicket> {
  bool isEdit = false;
  @override
  initState() {
    context.read<PrinterLoaderBloc>().add(
      const PrinterLoaderEvent.getByCode('ticket'),
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MultiBlocListener(
      listeners: [
        BlocListener<PrinterFormBloc, PrinterFormState>(
          listenWhen: (p, c) =>
              p.failureOrDeleteSuccess != c.failureOrDeleteSuccess,
          listener: (context, state) {
            state.failureOrDeleteSuccess.fold(
              () => null,
              (either) => either.fold(
                (f) => AppFlushbar.showPrinterFailureToast(context, f),
                (_) {
                  if (context.mounted) {
                    context.read<PrinterLoaderBloc>().add(
                      const PrinterLoaderEvent.getByCode('ticket'),
                    );
                  }

                  AppFlushbar.showSuccess(
                    context,
                    'Printer ticket berhasil dihapus',
                  );
                },
              ),
            );
          },
        ),
        BlocListener<PrinterFormBloc, PrinterFormState>(
          listenWhen: (p, c) => p.failureOrPrintTest != c.failureOrPrintTest,
          listener: (context, state) {
            state.failureOrPrintTest.fold(
              () => null,
              (either) => either.fold(
                (f) => AppFlushbar.showPrinterFailureToast(context, f),
                (either) {
                  AppFlushbar.showSuccess(context, 'Printer test berhasil');
                },
              ),
            );
          },
        ),
      ],
      child: Material(
        color: AppColor.background,
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: [
              BlocBuilder<PrinterLoaderBloc, PrinterLoaderState>(
                builder: (context, state) {
                  if (state.isFetching) {
                    return const Center(child: LoaderWithText());
                  }

                  if (state.printer.code == '') {
                    return SettingPrinterForm(
                      code: 'ticket',
                      onSuccess: () {
                        context.read<PrinterLoaderBloc>().add(
                          const PrinterLoaderEvent.getByCode('ticket'),
                        );
                      },
                    );
                  }

                  return state.failureOption.fold(
                    () => isEdit
                        ? SettingPrinterForm(
                            code: 'ticket',
                            printer: state.printer,
                            onCancel: () {
                              setState(() {
                                isEdit = false;
                              });
                            },
                            onSuccess: () {
                              context.read<PrinterLoaderBloc>().add(
                                const PrinterLoaderEvent.getByCode('ticket'),
                              );
                              setState(() {
                                isEdit = false;
                              });
                            },
                          )
                        : PrinterCard(
                            printer: state.printer,
                            onEdit: () {
                              setState(() {
                                isEdit = true;
                              });
                            },
                            onDelete: () => context.read<PrinterFormBloc>().add(
                              PrinterFormEvent.deleted(state.printer.id),
                            ),
                            onTestPrint: () =>
                                context.read<PrinterFormBloc>().add(
                                  PrinterFormEvent.printTest(
                                    code: 'ticket',
                                    macAccdress: state.printer.address,
                                  ),
                                ),
                          ),
                    (f) => f.maybeMap(
                      orElse: () => ErrorCard(
                        title: 'Error',
                        message: 'Terjadi Kesalahan',
                        onTap: () {},
                      ),
                      empty: (value) => SettingPrinterForm(
                        code: 'ticket',
                        onSuccess: () {
                          context.read<PrinterLoaderBloc>().add(
                            const PrinterLoaderEvent.getByCode('ticket'),
                          );
                        },
                      ),
                    ),
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}
