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

import '../../../../../../../application/printer/printer_form/printer_form_bloc.dart';
import '../../../../../../../common/data/printer_data.dart';
import '../../../../../../../common/extension/extension.dart';
import '../../../../../../../common/theme/theme.dart';
import '../../../../../../../domain/printer/printer.dart';
import '../../../../../../components/button/button.dart';
import '../../../../../../components/dialog/dialog.dart';
import '../../../../../../components/field/field.dart';
import '../../../../../../components/spaces/space.dart';
import '../../../../../../components/toast/flushbar.dart';

class SettingPrinterForm extends StatefulWidget {
  final String code;
  final Printer? printer;
  final Function()? onCancel;
  final Function()? onSuccess;

  const SettingPrinterForm({
    super.key,
    required this.code,
    this.printer,
    this.onCancel,
    this.onSuccess,
  });

  @override
  State<SettingPrinterForm> createState() => _SettingPrinterFormState();
}

class _SettingPrinterFormState extends State<SettingPrinterForm> {
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _networkController = TextEditingController();

  void setup() {
    if (widget.printer != null) {
      context.read<PrinterFormBloc>().add(
        PrinterFormEvent.typeChanged(widget.printer!.type),
      );
      context.read<PrinterFormBloc>().add(
        PrinterFormEvent.addressChanged(widget.printer!.address),
      );
      context.read<PrinterFormBloc>().add(
        PrinterFormEvent.codeChanged(widget.printer!.code),
      );
      context.read<PrinterFormBloc>().add(
        PrinterFormEvent.nameChanged(widget.printer!.name),
      );
      context.read<PrinterFormBloc>().add(
        PrinterFormEvent.paperChanged(widget.printer!.paper),
      );
      _nameController.text = widget.printer!.name;
      _networkController.text = widget.printer!.address;
    }
  }

  @override
  void initState() {
    setup();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MultiBlocListener(
      listeners: [
        BlocListener<PrinterFormBloc, PrinterFormState>(
          listenWhen: (p, c) =>
              p.failureOrCreateSuccess != c.failureOrCreateSuccess,
          listener: (context, state) {
            state.failureOrCreateSuccess.fold(
              () => null,
              (either) => either.fold(
                (f) => AppFlushbar.showPrinterFailureToast(context, f),
                (either) {
                  widget.onSuccess?.call();
                  AppFlushbar.showSuccess(
                    context,
                    'Printer ${widget.code.toTitleCase()} berhasil ditambahkan',
                  );
                },
              ),
            );
          },
        ),
        BlocListener<PrinterFormBloc, PrinterFormState>(
          listenWhen: (p, c) =>
              p.failureOrUpdateSuccess != c.failureOrUpdateSuccess,
          listener: (context, state) {
            state.failureOrUpdateSuccess.fold(
              () => null,
              (either) => either.fold(
                (f) => AppFlushbar.showPrinterFailureToast(context, f),
                (either) {
                  widget.onSuccess?.call();
                  AppFlushbar.showSuccess(
                    context,
                    'Printer ${widget.code.toTitleCase()} berhasil diubah',
                  );
                },
              ),
            );
          },
        ),
        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 ${widget.code.toTitleCase()} test berhasil',
                  );
                },
              ),
            );
          },
        ),
      ],
      child: BlocBuilder<PrinterFormBloc, PrinterFormState>(
        builder: (context, state) {
          return Container(
            padding: const EdgeInsets.all(16.0),
            decoration: BoxDecoration(
              color: AppColor.white,
              borderRadius: BorderRadius.circular(16.0),
            ),
            child: Column(
              children: [
                AppDropdownSearch<String>(
                  label: 'Tipe',
                  hintText: 'Printer Tipe',
                  items: printerTypes,
                  itemAsString: (value) => value,
                  selectedItem: state.type,
                  onChanged: (value) {
                    context.read<PrinterFormBloc>().add(
                      PrinterFormEvent.typeChanged(value!),
                    );
                  },
                ),
                const SpaceHeight(12),
                state.type == 'Bluetooth'
                    ? SizedBox(
                        width: double.infinity,
                        child: AppElevatedButton.outlined(
                          onPressed: () {
                            showDialog(
                              context: context,
                              builder: (context) => PrinterBluetoothDialog(
                                onSelected: (value) {
                                  context.read<PrinterFormBloc>().add(
                                    PrinterFormEvent.addressChanged(value),
                                  );
                                },
                              ),
                            );
                          },
                          label: state.address != '' ? state.address : 'Cari',
                        ),
                      )
                    : AppTextFormField(
                        label: 'Network',
                        controller: _networkController,
                        onChanged: (value) {
                          context.read<PrinterFormBloc>().add(
                            PrinterFormEvent.addressChanged(value),
                          );
                        },
                      ),
                const SpaceHeight(12),
                AppTextFormField(
                  label: 'Nama Printer',
                  controller: _nameController,
                  onChanged: (value) {
                    context.read<PrinterFormBloc>().add(
                      PrinterFormEvent.nameChanged(value),
                    );
                  },
                ),
                const SpaceHeight(12),
                AppDropdownSearch<String>(
                  label: 'Kertas',
                  hintText: 'Kertas Tipe',
                  items: paperTypes,
                  itemAsString: (value) => "$value mm",
                  selectedItem: state.paper,
                  onChanged: (value) {
                    context.read<PrinterFormBloc>().add(
                      PrinterFormEvent.paperChanged(value!),
                    );
                  },
                ),
                const SpaceHeight(20),
                Row(
                  children: [
                    if (widget.printer != null) ...[
                      Expanded(
                        child: AppElevatedButton.outlined(
                          onPressed: widget.onCancel,
                          label: 'Batal',
                        ),
                      ),
                      const SpaceWidth(12),
                    ],
                    Expanded(
                      child: AppElevatedButton.outlined(
                        onPressed: () {
                          context.read<PrinterFormBloc>().add(
                            PrinterFormEvent.printTest(
                              code: widget.code,
                              macAccdress: state.address,
                            ),
                          );
                        },
                        label: 'Test Print',
                      ),
                    ),
                    const SpaceWidth(12),
                    Expanded(
                      child: AppElevatedButton.filled(
                        onPressed: () {
                          if (widget.printer == null) {
                            if (!state.isCreating) {
                              context.read<PrinterFormBloc>().add(
                                PrinterFormEvent.codeChanged(widget.code),
                              );

                              context.read<PrinterFormBloc>().add(
                                const PrinterFormEvent.created(),
                              );
                            }
                          } else {
                            context.read<PrinterFormBloc>().add(
                              PrinterFormEvent.updated(widget.printer!.id),
                            );
                          }
                        },
                        label: widget.printer == null ? 'Simpan' : 'Ubah',
                        isLoading: widget.printer == null
                            ? state.isCreating
                            : state.isUpdate,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}
