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

import '../../../application/payment/payment_form/payment_form_bloc.dart';
import '../../../application/payment_method/payment_method_loader/payment_method_loader_bloc.dart';
import '../../../common/theme/theme.dart';
import '../../../common/types/split_type.dart';
import '../../../domain/order/order.dart';
import '../../../injection.dart';
import '../../components/spaces/space.dart';
import '../../components/toast/flushbar.dart';
import '../../router/app_router.gr.dart';
import 'widgets/payment_left_panel.dart';
import 'widgets/payment_right_panel.dart';

@RoutePage()
class PaymentPage extends StatelessWidget implements AutoRouteWrapper {
  final Order order;
  final bool isSplit;
  final SplitType splitType;
  final String? customerId;
  final String? customerName;
  const PaymentPage({
    super.key,
    required this.order,
    this.isSplit = false,
    this.splitType = SplitType.unknown,
    this.customerId,
    this.customerName,
  });

  @override
  Widget build(BuildContext context) {
    return MultiBlocListener(
      listeners: [
        BlocListener<PaymentFormBloc, PaymentFormState>(
          listenWhen: (p, c) => p.failureOrPayment != c.failureOrPayment,
          listener: (context, state) {
            state.failureOrPayment.fold(
              () {},
              (either) => either.fold(
                (f) => AppFlushbar.showOrderFailureToast(context, f),
                (data) {
                  if (context.mounted) {
                    context.router.replace(
                      PaymentSuccessRoute(orderId: order.id),
                    );
                  }
                },
              ),
            );
          },
        ),
        BlocListener<PaymentFormBloc, PaymentFormState>(
          listenWhen: (p, c) =>
              p.failureOrPaymentSplitBill != c.failureOrPaymentSplitBill,
          listener: (context, state) {
            state.failureOrPaymentSplitBill.fold(
              () {},
              (either) => either.fold(
                (f) => AppFlushbar.showOrderFailureToast(context, f),
                (data) {
                  if (context.mounted) {
                    context.router.replace(
                      PaymentSuccessSplitBillRoute(
                        orderId: order.id,
                        orderItems: order.orderItems,
                      ),
                    );
                  }
                },
              ),
            );
          },
        ),
      ],
      child: Scaffold(
        backgroundColor: AppColor.background,
        appBar: AppBar(
          backgroundColor: AppColor.white,
          elevation: 0,
          title: const Text(
            'Pembayaran',
            style: TextStyle(color: AppColor.primary),
          ),
          leading: IconButton(
            onPressed: () => context.router.maybePop(),
            icon: const Icon(Icons.arrow_back, color: AppColor.primary),
          ),
          actions: [
            if (isSplit)
              Container(
                padding: const EdgeInsets.all(4),
                margin: const EdgeInsets.only(right: 8),
                decoration: BoxDecoration(
                  border: Border.all(color: AppColor.primary),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Text(
                  "Split Bill: ${splitType.toStringType()}",
                  style: AppStyle.sm.copyWith(
                    fontWeight: FontWeight.w600,
                    color: AppColor.primary,
                  ),
                ),
              ),
          ],
        ),
        body: LayoutBuilder(
          builder: (context, constraints) {
            final isWide = constraints.maxWidth > 800;

            return BlocBuilder<PaymentFormBloc, PaymentFormState>(
              builder: (context, state) {
                return Padding(
                  padding: const EdgeInsets.all(16),
                  child: isWide
                      ? Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Expanded(
                              flex: 3,
                              child: PaymentLeftPanel(state: state),
                            ),
                            const SizedBox(width: 24),
                            Expanded(
                              flex: 2,
                              child: PaymentRightPanel(
                                state: state,
                                isSplit: isSplit,
                                splitType: splitType,
                                customerId: customerId,
                                customerName: customerName,
                              ),
                            ),
                          ],
                        )
                      : SingleChildScrollView(
                          child: Column(
                            children: [
                              PaymentLeftPanel(state: state),
                              const SpaceHeight(24),
                              PaymentRightPanel(
                                state: state,
                                isSplit: isSplit,
                                splitType: splitType,
                                customerId: customerId,
                                customerName: customerName,
                              ),
                            ],
                          ),
                        ),
                );
              },
            );
          },
        ),
      ),
    );
  }

  @override
  Widget wrappedRoute(BuildContext context) => MultiBlocProvider(
    providers: [
      BlocProvider(
        create: (context) =>
            getIt<PaymentFormBloc>()..add(PaymentFormEvent.setOrder(order)),
      ),
      BlocProvider(
        create: (context) =>
            getIt<PaymentMethodLoaderBloc>()
              ..add(const PaymentMethodLoaderEvent.fetched(isRefresh: true)),
      ),
    ],
    child: this,
  );
}
