import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:mc_common_app/classes/app_state.dart';
import 'package:mc_common_app/classes/consts.dart';
import 'package:mc_common_app/extensions/string_extensions.dart';
import 'package:mc_common_app/services/my_in_app_browser.dart';
import 'package:mc_common_app/utils/enums.dart';

abstract class PaymentService {
  Future<void> placePayment({
    required int id,
    List<int>? appointmentIds,
    required PaymentTypes paymentType,
    required Function() onSuccess,
    required Function() onFailure,
  });

  Future<void> onBrowserLoadStart({
    required String url,
    required Function() onSuccess,
    required Function() onFailure,
  });
}

class PaymentServiceImp implements PaymentService {
  MyInAppBrowser? myInAppBrowser;

  // var inAppBrowserOptions = InAppBrowserClassOptions(
  //     inAppWebViewGroupOptions:
  //         InAppWebViewGroupOptions(crossPlatform: InAppWebViewOptions(useShouldOverrideUrlLoading: true, transparentBackground: false), ios: IOSInAppWebViewOptions(applePayAPIEnabled: true)),
  //     crossPlatform: InAppBrowserOptions(hideUrlBar: true, toolbarTopBackgroundColor: Colors.black),
  //     android: AndroidInAppBrowserOptions(),
  //     ios:
  //         IOSInAppBrowserOptions(hideToolbarBottom: true, toolbarBottomBackgroundColor: Colors.white, closeButtonColor: Colors.white, presentationStyle: IOSUIModalPresentationStyle.OVER_FULL_SCREEN));

  var inAppBrowserOptions = InAppBrowserClassSettings(
    webViewSettings: InAppWebViewSettings(
      useShouldOverrideUrlLoading: false,
      transparentBackground: false,
      isInspectable: false,
      applePayAPIEnabled: true,
      cacheEnabled: false,
    ),
    browserSettings: InAppBrowserSettings(
      hideUrlBar: true,
      hideTitleBar: true,
      hideDefaultMenuItems: true,
      hideToolbarBottom: true,
      hideToolbarTop: false,
      hideCloseButton: false,
      allowGoBackWithBackButton: true,
      toolbarBottomBackgroundColor: Colors.black,
      closeButtonColor: Colors.white,
      presentationStyle: ModalPresentationStyle.FULL_SCREEN,
      //   toolbarTopBackgroundColor: Colors.black
    ),
  );

  String getUrlRequestByPaymentId({required int id, List<int>? appointmentIds, required PaymentTypes paymentType}) {
    String urlRequest = "";
    int customerId = AppState().getUser.data!.userInfo!.customerId ?? 0;

    switch (paymentType) {
      case PaymentTypes.subscription:
        urlRequest = "${ApiConsts.paymentWebViewUrl}?PaymentType=${paymentType.getIdFromPaymentTypesEnum()}&OrderProviderSubscriptionID=$id";
        break;
      case PaymentTypes.appointment:
      case PaymentTypes.partialAppointment:
        String appointIds = '';
        for (int i = 0; i < appointmentIds!.length; i++) {
          var element = appointmentIds[i];
          if (i == appointmentIds.length - 1) {
            appointIds = "$appointIds$element";
          } else {
            appointIds = "$appointIds$element:";
          }
        }
        urlRequest = "${ApiConsts.paymentWebViewUrl}?PaymentType=${paymentType.getIdFromPaymentTypesEnum()}&CustomerID=$customerId&AppointmentIDs=$appointIds";
        break;
      case PaymentTypes.adReserve:
        urlRequest = "${ApiConsts.paymentWebViewUrl}?PaymentType=${paymentType.getIdFromPaymentTypesEnum()}&CustomerID=$customerId&AdsID=$id";
        break;
      case PaymentTypes.ads:
        urlRequest = "${ApiConsts.paymentWebViewUrl}?PaymentType=${paymentType.getIdFromPaymentTypesEnum()}&CustomerID=$customerId&AdsID=$id";
        break;
      case PaymentTypes.extendAds:
        urlRequest = "${ApiConsts.paymentWebViewUrl}?PaymentType=${paymentType.getIdFromPaymentTypesEnum()}&CustomerID=$customerId&AdsID=$id";
        break;
      case PaymentTypes.request:
        urlRequest = "${ApiConsts.paymentWebViewUrl}?PaymentType=${paymentType.getIdFromPaymentTypesEnum()}&CustomerID=$customerId&RequestID=$id";
        break;
    }

    return urlRequest;
  }

  @override
  Future<void> placePayment({
    required int id,
    List<int>? appointmentIds,
    required PaymentTypes paymentType,
    required Function() onSuccess,
    required Function() onFailure,
  }) async {
    String urlRequest = getUrlRequestByPaymentId(id: id, paymentType: paymentType, appointmentIds: appointmentIds);
    log("PaymentUrl: $urlRequest");
    myInAppBrowser = MyInAppBrowser(onExitCallback: () {
      log("Browser Exited");
    }, onLoadStartCallback: (String url) {
      log("Browser LoadStart for :  $url");
      onBrowserLoadStart(onFailure: onFailure, onSuccess: onSuccess, url: url);
    });
    await myInAppBrowser!.openUrlRequest(
      // Uri.parse(urlRequest)
      urlRequest: URLRequest(url: WebUri(urlRequest)),
      settings: inAppBrowserOptions,
      // in: inAppBrowserOptions,
    );
  }

  @override
  Future<void> onBrowserLoadStart({
    required String url,
    required Function() onSuccess,
    required Function() onFailure,
  }) async {
    for (var element in ApiConsts.closingUrls) {
      if (url.contains(element)) {
        if (myInAppBrowser!.isOpened()) myInAppBrowser!.close();
        onSuccess();
        return;
      }
      // onFailure();
    }
  }
}
