import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:qpay/screens/transaction_controller.dart';
import 'package:qpay/widgets/step_loading_widget.dart';

import 'integration_controller.dart';

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

  @override
  State<IntegrationScreen> createState() => _IntegrationScreenState();
}

class _IntegrationScreenState extends State<IntegrationScreen> {
  late IntegrationController controller;
  late TransactionController transactionController;

  @override
  void initState() {
    super.initState();
    controller = IntegrationController(context);
    transactionController = Provider.of<TransactionController>(
      context,
      listen: false,
    );

    controller.doIntegration();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Completing your transaction'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => context.go('/'),
        ),
      ),
      body: ListenableBuilder(
        listenable: controller,
        builder: (context, child) {
          if (controller.model.status == 'SUCCESS') {
            final transactionId = controller.model.transaction?['id'];
            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (transactionId != null) {
                context.go('/receipt/$transactionId');
              } else {
                context.go('/receipt');
              }
            });
          }

          return StepLoadingWidget(
            currentStep: 2,
            title: 'Updating Account',
            subtitle:
                'We\'ve successfully collected your funds. We are now '
                'updating your billing account. This won\'t take long.',
            status: controller.model.status,
            isLoading: controller.model.isLoading,
            errorMessage: 'We failed to update your billing account',
            onRetry: () {
              controller.doIntegration();
            },
          );
        },
      ),
    );
  }
}
