import 'package:comwell_key_app/presentation/screens/check_in/bloc/check_in_cubit.dart';
import 'package:comwell_key_app/presentation/screens/check_in/bloc/check_in_state.dart';
import 'package:comwell_key_app/presentation/screens/check_in/components/check_in_bottom_sheet.dart';
import 'package:comwell_key_app/presentation/screens/check_in/pages/check_in_page_enum.dart';
import 'package:comwell_key_app/presentation/screens/check_in/pages/check_in_processing_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 CheckInFlow extends StatelessWidget {
  const CheckInFlow({super.key});

  @override
  Widget build(BuildContext context) {
    final cubit = context.read<CheckInCubit>();
    if (!cubit.state.isPaymentProcessingNeeded) {
      return const CheckInProcessingPage();
    } 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));
            // After payment, navigate to the actual check-in processing
            if (context.mounted) {
              context.push(AppRoutes.checkIn, extra: [cubit.booking, false]);
            }
          }
        },
        child: BlocBuilder<CheckInCubit, CheckInState>(
          builder: (context, state) {
            return Scaffold(
              appBar: ComwellAppBar(
                shouldShowProfileButton: false,
                onBackPressed: () {
                  final didScroll = cubit.onBackPressed();
                  if (!didScroll) context.pop();
                },
              ),
              bottomSheet: CheckInBottomSheet(state: state),
              backgroundColor: Colors.white,
              body: PageView(
                controller: cubit.pageController,
                key: const PageStorageKey("check_in_flow"),
                physics: const NeverScrollableScrollPhysics(),
                children:
                    CheckInFlowPage.getPages(ValueKey(state)).toList(),
              ),
            );
          },
        ),
      );
    }
  }
}