import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/models/LiveCare/ERAppointmentFeesResponse.dart';
import 'package:diplomaticquarterapp/models/LiveCare/LiveCareClinicsListResponse.dart';
import 'package:diplomaticquarterapp/pages/ToDoList/payment_method_select.dart';
import 'package:diplomaticquarterapp/pages/livecare/widgets/LiveCareInfoDialog.dart';
import 'package:diplomaticquarterapp/pages/livecare/widgets/LiveCarePaymentDialog.dart';
import 'package:diplomaticquarterapp/pages/livecare/widgets/clinic_card.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart';
import 'package:diplomaticquarterapp/services/livecare_services/livecare_provider.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/widgets/in_app_browser/InAppBrowser.dart';
import 'package:flutter/material.dart';
import 'package:smart_progress_bar/smart_progress_bar.dart';

class ClinicList extends StatefulWidget {
  final Function getLiveCareHistory;

  ClinicList({@required this.getLiveCareHistory});

  @override
  _clinic_listState createState() => _clinic_listState();
}

class _clinic_listState extends State<ClinicList> {
  int currentSelectedIndex = 0;
  LiveCareClinicsListResponse liveCareClinicsListResponse;

  bool isDataLoaded = false;
  var languageID;

  int selectedClinicID = 1;
  String selectedClinicName = "-";

  AppSharedPreferences sharedPref = AppSharedPreferences();

  AuthenticatedUser authUser;
  AuthProvider authProvider = new AuthProvider();

  MyInAppBrowser browser;

  @override
  void initState() {
    liveCareClinicsListResponse = new LiveCareClinicsListResponse();
    WidgetsBinding.instance.addPostFrameCallback((_) {
//      Future.delayed(new Duration(milliseconds: 1200), () {
      getLiveCareClinicsList();
//      });
    });
    getLanguageID();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          isDataLoaded
              ? Container(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.all(15.0),
                        child: Text("Online Clinics: ",
                            style: TextStyle(
                                fontSize: 20.0, fontWeight: FontWeight.bold)),
                      ),
                      ListView.builder(
                        scrollDirection: Axis.vertical,
                        shrinkWrap: true,
                        physics: ScrollPhysics(),
                        padding: EdgeInsets.all(0.0),
                        itemCount: liveCareClinicsListResponse
                            .patientERGetClinicsList.length,
                        itemBuilder: (context, index) {
                          return InkWell(
                            onTap: () {
                              updateSelectedIndex(liveCareClinicsListResponse
                                  .patientERGetClinicsList[index]);
                            },
                            child: ClinicCard(
                              isSelected: selectedClinicID ==
                                      liveCareClinicsListResponse
                                          .patientERGetClinicsList[index]
                                          .serviceID
                                  ? true
                                  : false,
                              patientERGetClinicsList:
                                  liveCareClinicsListResponse
                                      .patientERGetClinicsList[index],
                              languageID: languageID,
                            ),
                          );
                        },
                      ),
                      Container(
                        height: 10.0,
                      ),
                    ],
                  ),
                )
              : Container(),
          isDataLoaded ? Container(
            width: MediaQuery.of(context).size.width,
            height: 50.0,
            margin: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
            child: ButtonTheme(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10.0),
              ),
              minWidth: MediaQuery.of(context).size.width * 0.7,
              height: 45.0,
              child: RaisedButton(
                color: new Color(0xFF60686b),
                textColor: Colors.white,
                disabledTextColor: Colors.white,
                disabledColor: new Color(0xFFbcc2c4),
                onPressed: startLiveCare,
                child: Text("Start", style: TextStyle(fontSize: 18.0)),
              ),
            ),
          ) : Container(),
        ],
      ),
    );
  }

  void startLiveCare() {
    bool isError = false;
    LiveCareService service = new LiveCareService();
    ERAppointmentFeesResponse erAppointmentFeesResponse =
        new ERAppointmentFeesResponse();
    service
        .getERAppointmentFees(selectedClinicID, context)
        .then((res) {
          erAppointmentFeesResponse = ERAppointmentFeesResponse.fromJson(res);
        })
        .catchError((err) {
          print(err);
          isError = true;
          AppToast.showErrorToast(message: err);
        })
        .showProgressBar(
            text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6))
        .then((value) {
          if (!isError)
            getERAppointmentTime(
                erAppointmentFeesResponse.getERAppointmentFeesList);
        });
  }

  getERAppointmentTime(GetERAppointmentFeesList getERAppointmentFeesList) {
    LiveCareService service = new LiveCareService();
    service.getERAppointmentTime(selectedClinicID, context).then((res) {
      print(res['WatingtimeInteger']);
      showLiveCarePaymentDialog(
          getERAppointmentFeesList, res['WatingtimeInteger']);
    }).catchError((err) {
      print(err);
      AppToast.showErrorToast(message: err);
    }).showProgressBar(
        text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }

  showLiveCarePaymentDialog(
      GetERAppointmentFeesList getERAppointmentFeesList, int waitingTime) {
    showGeneralDialog(
            barrierColor: Colors.black.withOpacity(0.5),
            transitionBuilder: (context, a1, a2, widget) {
              final curvedValue =
                  Curves.easeInOutBack.transform(a1.value) - 1.0;
              return Transform(
                transform:
                    Matrix4.translationValues(0.0, curvedValue * 200, 0.0),
                child: Opacity(
                  opacity: a1.value,
                  child: LiveCarePaymentDialog(
                      getERAppointmentFeesList: getERAppointmentFeesList,
                      waitingTime: waitingTime,
                      clinicName: selectedClinicName),
                ),
              );
            },
            transitionDuration: Duration(milliseconds: 500),
            barrierDismissible: true,
            barrierLabel: '',
            context: context,
            pageBuilder: (context, animation1, animation2) {})
        .then((value) {
      if (value) {
        if (getERAppointmentFeesList.total == "0" ||
            getERAppointmentFeesList.total == "0.0") {
          showLiveCareInfoDialog(getERAppointmentFeesList);
        } else {
          navigateToPaymentMethod(getERAppointmentFeesList, context);
        }
      }
    });
  }

  showLiveCareInfoDialog(
      GetERAppointmentFeesList getERAppointmentFeesList) async {
    if (await this.sharedPref.getObject(USER_PROFILE) != null) {
      var data = AuthenticatedUser.fromJson(
          await this.sharedPref.getObject(USER_PROFILE));
      setState(() {
        authUser = data;
      });
    }

    showGeneralDialog(
            barrierColor: Colors.black.withOpacity(0.5),
            transitionBuilder: (context, a1, a2, widget) {
              final curvedValue =
                  Curves.easeInOutBack.transform(a1.value) - 1.0;
              return Transform(
                transform:
                    Matrix4.translationValues(0.0, curvedValue * 200, 0.0),
                child: Opacity(
                  opacity: a1.value,
                  child: LiveCareInfoDialog(),
                ),
              );
            },
            transitionDuration: Duration(milliseconds: 500),
            barrierDismissible: true,
            barrierLabel: '',
            context: context,
            pageBuilder: (context, animation1, animation2) {})
        .then((value) {
      if (value) {
        if (getERAppointmentFeesList.total == "0" ||
            getERAppointmentFeesList.total == "0.0") {
          addNewCallForPatientER(authUser.patientID.toString() +
              "" +
              DateTime.now().millisecondsSinceEpoch.toString());
        } else {
          navigateToPaymentMethod(getERAppointmentFeesList, context);
        }
      }
    });
  }

  Future navigateToPaymentMethod(
      GetERAppointmentFeesList getERAppointmentFeesList, context) async {
    AppoitmentAllHistoryResultList appo = new AppoitmentAllHistoryResultList();

    appo.clinicID = selectedClinicID;
    appo.appointmentNo = DateTime.now().millisecondsSinceEpoch;

    if (await this.sharedPref.getObject(USER_PROFILE) != null) {
      var data = AuthenticatedUser.fromJson(
          await this.sharedPref.getObject(USER_PROFILE));
      setState(() {
        authUser = data;
      });
    }

    Navigator.push(
            context, MaterialPageRoute(builder: (context) => PaymentMethod()))
        .then((value) {
      print(value);
      if (value != null) {
        openPayment(value, authUser,
            double.parse(getERAppointmentFeesList.total), appo);
      }
    });
  }

  openPayment(String paymentMethod, AuthenticatedUser authenticatedUser,
      double amount, AppoitmentAllHistoryResultList appo) {
    browser = new MyInAppBrowser(
        onExitCallback: onBrowserExit,
        appo: appo,
        onLoadStartCallback: onBrowserLoadStart);

    browser.openPaymentBrowser(
        amount,
        "LiveCare Payment",
        Utils.getAppointmentTransID(12, appo.clinicID, appo.appointmentNo),
        "12",
        authenticatedUser.emailAddress,
        paymentMethod,
        authenticatedUser,
        browser);
  }

  onBrowserLoadStart(String url) {
    print("onBrowserLoadStart");
    print(url);

    MyInAppBrowser.successURLS.forEach((element) {
      if (url.contains(element)) {
        if (browser.isOpened()) browser.close();
        MyInAppBrowser.isPaymentDone = true;
        return;
      }
    });

    MyInAppBrowser.errorURLS.forEach((element) {
      if (url.contains(element)) {
        if (browser.isOpened()) browser.close();
        MyInAppBrowser.isPaymentDone = false;
        return;
      }
    });
  }

  onBrowserExit(AppoitmentAllHistoryResultList appo, bool isPaymentMade) {
    print("onBrowserExit Called!!!!");
    if (isPaymentMade) checkPaymentStatus(appo);
  }

  checkPaymentStatus(AppoitmentAllHistoryResultList appo) {
    DoctorsListService service = new DoctorsListService();
    service
        .checkPaymentStatus(
            Utils.getAppointmentTransID(
                appo.projectID, appo.clinicID, appo.appointmentNo),
            context)
        .then((res) {
      print("Printing Payment Status Reponse!!!!");
      print(res);
      String paymentInfo = res['Response_Message'];
      if (paymentInfo == 'Success') {
        addNewCallForPatientER(Utils.getAppointmentTransID(
            appo.projectID, appo.clinicID, appo.appointmentNo));
      } else {
        AppToast.showErrorToast(message: res['Response_Message']);
      }
    }).catchError((err) {
      print(err);
    }).showProgressBar(
            text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }

  addNewCallForPatientER(String clientRequestID) {
    LiveCareService service = new LiveCareService();
    service
        .addNewCallForPatientER(selectedClinicID, clientRequestID, context)
        .then((res) {
          AppToast.showSuccessToast(
              message: "New Call has been added successfully");
        })
        .catchError((err) {
          print(err);
        })
        .showProgressBar(
            text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6))
        .then((value) {
          widget.getLiveCareHistory();
        });
  }

  getLanguageID() async {
    languageID = await sharedPref.getString(APP_LANGUAGE);
  }

  getLiveCareClinicsList() {
    isDataLoaded = false;
    LiveCareService service = new LiveCareService();
    service.getLivecareClinics(context).then((res) {
      print(res['PatientER_GetClinicsList'].length);
      if (res['MessageStatus'] == 1) {
        setState(() {
          liveCareClinicsListResponse =
              LiveCareClinicsListResponse.fromJson(res);
          print(liveCareClinicsListResponse.patientERGetClinicsList.length);
          selectedClinicID =
              liveCareClinicsListResponse.patientERGetClinicsList[0].serviceID;
          selectedClinicName = liveCareClinicsListResponse
              .patientERGetClinicsList[0].serviceName;
          isDataLoaded = true;
        });
      } else {
        isDataLoaded = true;
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      print(err);
    }).showProgressBar(
        text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }

  updateSelectedIndex(PatientERGetClinicsList patientERGetClinicsList) {
    setState(() {
      selectedClinicID = patientERGetClinicsList.serviceID;
      selectedClinicName = patientERGetClinicsList.serviceName;
    });
  }
}
