import 'package:comwell_key_app/check_out/bloc/check_out_cubit.dart';
import 'package:comwell_key_app/check_out/components/check_out_bottom_sheet.dart';
import 'package:comwell_key_app/check_out/pages/check_out_processing_page.dart';
import 'package:comwell_key_app/check_out/pages/check_out_page.dart';
import 'package:comwell_key_app/common/components/comwell_app_bar.dart';
import 'package:comwell_key_app/routing/app_routes.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:payment_plugin/presentation/app/bloc/payment_cubit.dart';
import 'package:payment_plugin/presentation/app/bloc/payment_processing_state.dart';

class CheckOutFlow extends StatelessWidget {
  const CheckOutFlow({super.key});

  @override
  Widget build(BuildContext context) {
    final cubit = context.read<CheckoutCubit>();
    if (!cubit.state.isPaymentProcessingNeeded) {
      return const CheckOutProcessingPage();
    } else {
      return BlocListener<PaymentCubit, PaymentProcessingState>(
        listenWhen: (previous, current) => previous is! PaymentProcessingStateConfirmed && current is PaymentProcessingStateConfirmed,
        listener: (context, state) async {
          if (state is PaymentProcessingStateConfirmed) {
            //This is here to add time so that the payment is represented in the BookingDetails
            await Future<void>.delayed(const Duration(seconds: 1));
            await cubit.checkOut();
            if (cubit.state.successfulCheckout && context.mounted) {
              context.push(
                AppRoutes.checkOutSuccess,
                extra: [cubit.booking.digitalCard, cubit.booking],
              );
            } else if (cubit.state.hasCheckoutError && context.mounted) {
              context.push(AppRoutes.checkOutError, extra: cubit.booking);
            }
          }
        },
        child: Scaffold(
          appBar: ComwellAppBar(
            shouldShowProfileButton: false,
            onBackPressed: () {
              final didScroll = cubit.onBackPressed();
              if (!didScroll) context.pop();
            },
          ),
          bottomSheet: CheckOutBottomSheet(state: cubit.state),
          backgroundColor: Colors.white,
          body: PageView(
            controller: cubit.pageController,
            key: const PageStorageKey("check_out_flow"),
            physics: const NeverScrollableScrollPhysics(),
            children: CheckoutPage.getPages(ValueKey(cubit.state)).toList(),
          ),
        ),
      );
    }
  }
}