import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:provider/provider.dart';
import 'package:qpay/http/http.dart';
import 'package:qpay/models/api_response.dart';
import 'package:qpay/screens/pay/pay_controller.dart' as pc;
import 'package:qpay/screens/transaction_controller.dart' as tc;
import 'package:qpay/screens/home/home_controller.dart' as hc;
import 'package:qpay/screens/transactions/transaction_model.dart';

class ReceiptModel {
  TransactionModel? transaction;
  bool isLoading = false;
  String? errorMessage;
  String status = '';
}

class ReceiptController extends ChangeNotifier {
  final ReceiptModel model = ReceiptModel();
  final Http http = Http();
  late tc.TransactionController transactionController;
  late SharedPreferences prefs;

  BuildContext context;

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

  void setLoading(bool value) {
    model.isLoading = value;
    notifyListeners();
  }

  Future<ApiResponse<TransactionModel>> doIntegration(String id) async {
    try {
      model.isLoading = true;
      model.status = '';
      notifyListeners();

      dynamic workflowResponse = await http.get(
        '/public/transaction/integration/$id',
      );
      logger.i(workflowResponse.toString());

      dynamic response = workflowResponse['body'];
      model.isLoading = false;

      if (response['status'] == 'SUCCESS') {
        model.status = response['status'];
        transactionController.updateReceiptData(
          Map<String, dynamic>.from(response),
        );
        notifyListeners();
        return ApiResponse.success(
          TransactionModel.fromJson(Map<String, dynamic>.from(response)),
        );
      } else {
        model.status = response['status'];
        model.errorMessage = response['errorMessage'];
        notifyListeners();
        return ApiResponse.failure(
          response['errorMessage'] ?? "Integration failed",
        );
      }
    } catch (e) {
      model.isLoading = false;
      model.errorMessage = e.toString();
      notifyListeners();
      return ApiResponse.failure(e.toString());
    }
  }

  Future<void> repeatTransaction(TransactionModel transaction) async {
    setLoading(true);
    // fetch provider & update tran controller
    String providerId = transaction.billClientId ?? '';
    Map<String, dynamic> provider = await http.get(
      '/public/providers/client/$providerId',
    );
    transactionController.updateSelectedProvider(
      hc.BillProvider.fromJson(provider),
    );

    // update tran controller formdata with credit account, email, name, phone & providerLabel
    transactionController.model.formData = transactionController.model.formData
        .copyWith(
          creditAccount: transaction.creditAccount ?? '',
          creditPhone: transaction.creditPhone ?? '',
          creditName: transaction.creditName ?? '',
          creditEmail: transaction.creditEmail ?? '',
        );

    // fetch product and update tran controller formdata
    String providerUid = transactionController.model.selectedProvider?.id ?? '';
    String productName = transaction.billProductName ?? '';

    if (productName.isNotEmpty) {
      Map<String, dynamic> product = await http.get(
        '/public/providers/$providerUid/products/$productName',
      );
      transactionController.updateSelectedProduct(
        pc.BillProduct.fromJson(product),
      );
    }

    transactionController.updateCurrency(transaction.debitCurrency);

    // update credit amount, notification phone number, payment processor
    transactionController.model.formData = transactionController.model.formData
        .copyWith(
          amount: transaction.amount.toStringAsFixed(2),
          debitPhone: transaction.debitPhone,
          paymentProcessorLabel: transaction.paymentProcessorLabel,
          paymentProcessorName: transaction.paymentProcessorName,
          id: null,
        );

    setLoading(false);
  }

  Future<ApiResponse<TransactionModel>> getReceiptData(String id) async {
    setLoading(true);

    final prefs = await SharedPreferences.getInstance();
    try {
      Map<String, dynamic> response = await http.get(
        '/public/transaction/$id?workspaceId=${prefs.getString("workspaceId")}',
      );
      final transaction = TransactionModel.fromJson(response);
      model.transaction = transaction;
      setLoading(false);
      return ApiResponse.success(transaction);
    } catch (e, s) {
      print(e);
      print(s);
      setLoading(false);
      return ApiResponse.failure(
        "Problem fetching transaction data, are you connected to the internet?",
      );
    }
  }

  void updateReceiptTransaction(TransactionModel data) {
    model.transaction = data;
    notifyListeners();
  }
}
