import 'package:adyen_checkout/adyen_checkout.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:lottie/lottie.dart';
import 'package:payment_plugin/presentation/app/bloc/payment_cubit.dart';
import 'package:payment_plugin/presentation/app/bloc/payment_processing_state.dart';
import 'package:payment_plugin/themes/light_theme.dart';
import 'package:payment_plugin/utils/lottie_utils.dart';

class PaymentProcessingPage extends StatefulWidget {
  const PaymentProcessingPage({super.key});

  @override
  State<PaymentProcessingPage> createState() => _PaymentProcessingPageState();
}

class _PaymentProcessingPageState extends State<PaymentProcessingPage>
    with SingleTickerProviderStateMixin {
  LottieComposition? loadingComposition;
  late final AnimationController animationController;

  @override
  void initState() {
    animationController = AnimationController(vsync: this);
    super.initState();
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  void onAnimationEnd() {
    playLoading();
  }

  void playLoading() {
    loadingComposition?.playBetween(
      animationController,
      "spinner",
      markerEnd: "success",
      repeat: true,
    );
  }

  void playError() async {
    loadingComposition?.playBetween(animationController, "error", repeat: true);
    await Future<void>.delayed(const Duration(seconds: 2));
    if (mounted) Navigator.of(context).pop();
  }

  void playSuccess() async {
    await loadingComposition?.playBetween(
      animationController,
      "success",
      markerEnd: "error",
    );
    await Future<void>.delayed(const Duration(seconds: 1));
    if (mounted) Navigator.of(context).pop();
  }

  void showAdyenModal(BuildContext context) async {
    final cubit = context.read<PaymentCubit>();
    final processingState = cubit.state;
    dynamic response;
    if (processingState is! PaymentProcessingStateSessionReceived) return;
    final paymentConfig = processingState.paymentConfigurations;
    if (!mounted) return;

    final dropInConfig = paymentConfig.dropInConfiguration;
    response = await AdyenCheckout.session.startDropIn(
      dropInConfiguration: dropInConfig,
      checkout: paymentConfig.sessionCheckout,
    );

    if (!mounted) return;
    if (response is PaymentResult) {
      cubit.onPaymentResult(response);
    } else {
      cubit.onUserDismissPaymentPopup();
    }
  }

  @override
  Widget build(BuildContext context) {
    final cubit = context.watch<PaymentCubit>();
    return Scaffold(
      body: Container(
        alignment: Alignment.center,
        color: sandColor[80],
        child: BlocListener<PaymentCubit, PaymentProcessingState>(
          listenWhen: (prev, curr) => prev != curr,
          listener: (context, state) {
            if (state is PaymentProcessingStateSessionReceived) {
              showAdyenModal(context);
            } else if (state is PaymentProcessingStateError) {
              playError();
            }
          },
          child: Lottie.asset(
            'assets/animations/load_animation.json',
            controller: animationController,
            onLoaded: (composition) {
              if (loadingComposition == null) {
                loadingComposition = composition;
                animationController.duration = composition.duration;
                switch (cubit.state) {
                  case PaymentProcessingStateConfirmed _:
                    playSuccess();
                  case PaymentProcessingStateError _:
                    playError();
                  default:
                    playLoading();
                }
              }
            },
            fit: BoxFit.cover,
            width: 64,
            height: 64,
          ),
        ),
      ),
    );
  }
}