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

import '../../../../application/checkout/checkout_form/checkout_form_bloc.dart';
import '../../../../application/order/order_form/order_form_bloc.dart';
import '../../../../application/payment_method/payment_method_loader/payment_method_loader_bloc.dart';
import '../../../../application/table/table_loader/table_loader_bloc.dart';
import '../../../../common/extension/extension.dart';
import '../../../../common/theme/theme.dart';
import '../../../components/button/button.dart';
import '../../../components/card/payment_card.dart';
import '../../../components/dialog/order/order_save_dialog.dart';
import '../../../components/error/payment_method_error_state_widget.dart';
import '../../../components/field/field.dart';
import '../../../components/loader/loader_with_text.dart';
import '../../../components/page/page_title.dart';
import '../../../components/spaces/space.dart';
import '../../../components/toast/flushbar.dart';

class CheckoutRightPanel extends StatefulWidget {
  final CheckoutFormState checkoutState;
  final int price;
  const CheckoutRightPanel({
    super.key,
    required this.checkoutState,
    required this.price,
  });

  @override
  State<CheckoutRightPanel> createState() => _CheckoutRightPanelState();
}

class _CheckoutRightPanelState extends State<CheckoutRightPanel> {
  TextEditingController customerController = TextEditingController();
  TextEditingController totalPriceController = TextEditingController();

  int priceValue = 0;
  int pasMoney1 = 0;
  int pasMoney2 = 0;
  int pasMoney3 = 0;

  initMoney() {
    setState(() {
      priceValue = widget.price;
      pasMoney1 = widget.price;
      pasMoney2 = pasMoney1 ~/ 50000 * 50000 + 50000;
      pasMoney3 = pasMoney1 ~/ 50000 * 50000 + 100000;
      totalPriceController.text = widget.price.currencyFormatRpV2;
    });
  }

  @override
  void initState() {
    super.initState();
    initMoney();
    customerController.addListener(() {
      context.read<OrderFormBloc>().add(
        OrderFormEvent.customerNameChanged(customerController.text),
      );
      context.read<CheckoutFormBloc>().add(CheckoutFormEvent.customerNameChanged(customerController.text));
    });
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<OrderFormBloc, OrderFormState>(
      builder: (context, orderState) {
        return Column(
          children: [
            const PageTitle(
              title: 'Pembayaran',
              isBack: false,
              subtitle: 'Silahkan lakukan pembayaran',
            ),
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(16),
                      decoration: const BoxDecoration(
                        color: AppColor.white,
                        border: Border(
                          bottom: BorderSide(
                            color: AppColor.border,
                            width: 1.0,
                          ),
                        ),
                      ),
                      child: CustomerAutocomplete(
                        controller: customerController,
                        selectedCustomer: orderState.customer,
                        onSelected: (customer) {
                          context.read<OrderFormBloc>().add(
                            OrderFormEvent.customerChanged(customer),
                          );
                        },
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.all(16),
                      width: double.infinity,
                      decoration: const BoxDecoration(
                        color: AppColor.white,
                        border: Border(
                          bottom: BorderSide(
                            color: AppColor.border,
                            width: 1.0,
                          ),
                        ),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'Metode Pembayaran',
                            style: AppStyle.lg.copyWith(
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          const SpaceHeight(12.0),
                          BlocBuilder<
                            PaymentMethodLoaderBloc,
                            PaymentMethodLoaderState
                          >(
                            builder: (context, state) {
                              if (state.isFetching) {
                                return const Center(child: LoaderWithText());
                              }
                              return state.failureOption.fold(
                                () => Wrap(
                                  spacing: 12.0,
                                  runSpacing: 8.0,
                                  children: state.paymentMethods.map((item) {
                                    // Set default selected payment method if none selected or if current selection is not in the list
                                    if (orderState.paymentMethod == null ||
                                        !state.paymentMethods.any(
                                          (method) =>
                                              method.id ==
                                              orderState.paymentMethod?.id,
                                        )) {
                                      context.read<OrderFormBloc>().add(
                                        OrderFormEvent.paymentMethodChanged(
                                          state.paymentMethods.first,
                                        ),
                                      );
                                    }

                                    return PaymentCard(
                                      payment: item,
                                      isSelected:
                                          orderState.paymentMethod == item,
                                      onSelected: (_) {
                                        context.read<OrderFormBloc>().add(
                                          OrderFormEvent.paymentMethodChanged(
                                            item,
                                          ),
                                        );
                                      },
                                    );
                                  }).toList(),
                                ),
                                (f) =>
                                    PaymentMethodErrorStateWidget(failure: f),
                              );
                            },
                          ),
                        ],
                      ),
                    ),
                    if (orderState.paymentMethod != null &&
                        orderState.paymentMethod!.type == 'cash')
                      Container(
                        padding: const EdgeInsets.all(16),
                        decoration: const BoxDecoration(
                          color: AppColor.white,
                          border: Border(
                            bottom: BorderSide(
                              color: AppColor.border,
                              width: 1.0,
                            ),
                          ),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'Total Bayar',
                              style: AppStyle.lg.copyWith(
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                            const SpaceHeight(8.0),
                            AppTextFormField(
                              label: 'Total Bayar',
                              showLabel: false,
                              keyboardType: TextInputType.number,
                              controller: totalPriceController,
                              onChanged: (value) {
                                priceValue = value.toIntegerFromText;
                                final int newValue = value.toIntegerFromText;
                                totalPriceController.text =
                                    newValue.currencyFormatRp;
                                totalPriceController
                                    .selection = TextSelection.fromPosition(
                                  TextPosition(
                                    offset: totalPriceController.text.length,
                                  ),
                                );
                              },
                            ),
                            const SpaceHeight(20.0),
                            SingleChildScrollView(
                              scrollDirection: Axis.horizontal,
                              child: Row(
                                children: [
                                  AppElevatedButton.outlined(
                                    width: 150.0,
                                    onPressed: () {
                                      totalPriceController.text = pasMoney1
                                          .toString()
                                          .currencyFormatRpV2;
                                      priceValue = pasMoney1;
                                    },
                                    label: 'UANG PAS',
                                  ),
                                  const SpaceWidth(20.0),
                                  AppElevatedButton.outlined(
                                    width: 150.0,
                                    onPressed: () {
                                      totalPriceController.text = pasMoney2
                                          .toString()
                                          .currencyFormatRpV2;
                                      priceValue = pasMoney2;
                                    },
                                    label: pasMoney2
                                        .toString()
                                        .currencyFormatRpV2,
                                  ),
                                  const SpaceWidth(20.0),
                                  AppElevatedButton.outlined(
                                    width: 150.0,
                                    onPressed: () {
                                      totalPriceController.text = pasMoney3
                                          .toString()
                                          .currencyFormatRpV2;
                                      priceValue = pasMoney3;
                                    },
                                    label: pasMoney3
                                        .toString()
                                        .currencyFormatRpV2,
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                  ],
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.all(16),
              decoration: const BoxDecoration(
                color: AppColor.white,
                border: Border(
                  top: BorderSide(color: AppColor.border, width: 1.0),
                ),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: AppElevatedButton.outlined(
                      onPressed: () => context.router.maybePop(),
                      label: 'Batalkan',
                    ),
                  ),
                  const SpaceWidth(12),
                  Expanded(
                    child: BlocBuilder<TableLoaderBloc, TableLoaderState>(
                      builder: (context, tableState) {
                        return AppElevatedButton.filled(
                          isLoading: tableState.isFetching,
                          onPressed: () {
                            if (customerController.text == '') {
                              AppFlushbar.showError(
                                context,
                                'Pilih Pelanggan terlebih dahulu',
                              );
                              return;
                            }

                            showDialog(
                              context: context,
                              builder: (dcontext) => OrderSaveDialog(
                                checkoutState: widget.checkoutState,
                                tables: tableState.tables,
                              ),
                            );
                          },
                          label: 'Simpan',
                        );
                      },
                    ),
                  ),
                  const SpaceWidth(12),
                  Expanded(
                    child: AppElevatedButton.filled(
                      isLoading: orderState.isCreatingWithPayment,
                      onPressed: orderState.isCreatingWithPayment
                          ? null
                          : () {
                              if (customerController.text == '') {
                                AppFlushbar.showError(
                                  context,
                                  'Pilih Pelanggan terlebih dahulu',
                                );
                                return;
                              }

                              context.read<OrderFormBloc>().add(
                                OrderFormEvent.createOrderWithPayment(
                                  items: widget.checkoutState.items,
                                  orderType: widget.checkoutState.orderType,
                                  table: widget.checkoutState.table,
                                ),
                              );
                            },

                      label: 'Bayar',
                    ),
                  ),
                ],
              ),
            ),
          ],
        );
      },
    );
  }
}
