import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:qpay/http/http.dart';
import 'package:qpay/models/api_response.dart';
import 'package:qpay/screens/gateway/gateway_controller.dart';
import 'package:qpay/screens/transaction_controller.dart';
import 'package:shared_preferences/shared_preferences.dart';

class IntegrationModel {
  Map<String, dynamic>? transaction;
  String status = '';
  bool isLoading = false;
  String? errorMessage;
}

class IntegrationController extends ChangeNotifier {
  final IntegrationModel model = IntegrationModel();
  final Http http = Http();
  late TransactionController transactionController;
  late GatewayController gatewayController;
  late SharedPreferences prefs;

  bool _disposed = false;

  BuildContext context;

  IntegrationController(this.context) {
    transactionController = Provider.of<TransactionController>(
      context,
      listen: false,
    );

    gatewayController = GatewayController(context);
  }

  Future<ApiResponse<Map<String, dynamic>>> doIntegration() async {
    try {
      model.isLoading = true;
      notifyListeners();

      dynamic workflowResponse = await http.get(
        '/public/transaction/integration/'
        '${transactionController.model.confirmationData['id']}',
      );
      logger.i(workflowResponse.toString());

      dynamic response = workflowResponse['body'];

      String? transactionId;
      if (response['status'] == 'SUCCESS') {
        model.status = response['status'];
        transactionId = response['id'];
        transactionController.updateReceiptData(response);

        await gatewayController.poll(
          transactionController.model.confirmationData['id'],
        );
      }

      // regardless of poll result we proceed to receipt
      model.isLoading = false;
      if (!_disposed) notifyListeners();

      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (!_disposed && context.mounted) {
          if (transactionId != null) {
            context.go('/receipt/$transactionId');
          } else {
            context.go('/receipt');
          }
        }
      });

      return ApiResponse.success(Map<String, dynamic>.from(response));
    } catch (e) {
      model.isLoading = false;
      model.errorMessage = e.toString();
      if (!_disposed) notifyListeners();
      return ApiResponse.failure(e.toString());
    }
  }

  @override
  void dispose() {
    _disposed = true;
    super.dispose();
  }
}
