import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart';
import 'package:diplomaticquarterapp/models/Appointments/PatientShareResposne.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/pages/ToDoList/payment_method_select.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.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';

import 'QRCode.dart';

class BookSuccess extends StatefulWidget {
  PatientShareResponse patientShareResponse;
  DoctorList docObject;

  MyInAppBrowser browser;

  String appoDateFormatted;
  String appoTimeFormatted;

  BookSuccess(
      {@required this.patientShareResponse,
      @required this.docObject,
      @required this.appoDateFormatted,
      @required this.appoTimeFormatted});

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

class _BookSuccessState extends State<BookSuccess> {
  AppSharedPreferences sharedPref = AppSharedPreferences();
  AuthenticatedUser authUser;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            Container(
              width: MediaQuery.of(context).size.width,
              padding: EdgeInsets.only(bottom: 10.0),
              color: new Color(0xFF20bc44),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(top: 40.0),
                    child: Text(TranslationBase.of(context).bookSuccess,
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 18.0,
                            fontWeight: FontWeight.bold,
                            letterSpacing: 0.9)),
                  ),
                  Container(
                    margin: EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 20.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          padding: EdgeInsets.all(10.0),
                          child: Image.asset(
                              "assets/images/new-design/check-icon.png",
                              fit: BoxFit.fill,
                              height: 80.0,
                              width: 80.0),
                        ),
                        Container(
                          margin: EdgeInsets.fromLTRB(10.0, 5.0, 10.0, 5.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisSize: MainAxisSize.max,
                            children: <Widget>[
                              Text(widget.docObject.projectName,
                                  style: _getTextStyling()),
                              Container(
                                margin: EdgeInsets.only(top: 5.0),
                                child:
                                    Text("Insurance", style: _getTextStyling()),
                              ),
                              Container(
                                margin: EdgeInsets.only(top: 5.0, bottom: 3.0),
                                child: Text(widget.docObject.clinicName,
                                    style: _getTextStyling()),
                              ),
                              Container(
                                margin: EdgeInsets.only(top: 5.0, bottom: 3.0),
                                child: Text(
                                    widget.appoDateFormatted +
                                        ", " +
                                        widget.appoTimeFormatted,
                                    style: _getTextStyling()),
                              ),
                              Container(
                                width: MediaQuery.of(context).size.width * 0.65,
                                margin: EdgeInsets.only(top: 5.0, bottom: 3.0),
                                child: Text(
                                    widget.docObject.doctorTitle +
                                        " " +
                                        widget.docObject.name,
                                    overflow: TextOverflow.ellipsis,
                                    style: _getTextStyling()),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        border: Border.all(color: Colors.white, width: 0.5)),
                    margin: EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 10.0),
                    child: Table(
                      border: TableBorder(
                          verticalInside:
                              BorderSide(width: 0.5, color: Colors.white)),
                      children: [
                        TableRow(children: [
                          TableCell(
                              child: _getNormalText(
                                  TranslationBase.of(context).patientShare)),
                          TableCell(
                              child: _getNormalText(TranslationBase.of(context)
                                  .patientShareWithTax)),
                        ]),
                        TableRow(children: [
                          TableCell(
                              child: _getHeadingText("SR " +
                                  widget.patientShareResponse.patientShare
                                      .toString())),
                          TableCell(
                              child: _getHeadingText("SR " +
                                  widget
                                      .patientShareResponse.patientShareWithTax
                                      .toString())),
                        ]),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            getNextActionWidget(),
          ],
        ),
      ),
    );
  }

  Widget getNextActionWidget() {
    switch (widget.patientShareResponse.nextAction) {
      case 0:
        return Container();
        break;
      case 10:
        return _getConfirmAppo();
        break;
      case 15:
        return _getPaymentPendingAppo();
        break;
      case 20:
        return _getPayNowAppo();
        break;
      case 30:
        return _getQRAppo();
        break;
    }
  }

  String getNextAction() {
    switch (widget.patientShareResponse.nextAction) {
      case 0:
        return 'No Action';
        break;
      case 10:
        return 'Confirm';
        break;
      case 15:
        return 'Payment Pending';
        break;
      case 20:
        return 'Pay Now';
        break;
      case 30:
        return 'QR Code';
        break;
    }
  }

  Widget _getConfirmAppo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 30.0, bottom: 40.0),
          alignment: Alignment.center,
          child: Text(TranslationBase.of(context).confirmAppo,
              style: TextStyle(fontSize: 18.0, letterSpacing: 0.8)),
        ),
        Flex(
          direction: Axis.horizontal,
          children: <Widget>[
            Expanded(
              child: Container(
                padding: EdgeInsets.only(left: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    _getBulletPoint("1"),
                    Container(
                      child: Text(
                          "Please confirm the appointment to avoid the cancellation",
                          overflow: TextOverflow.fade,
                          style: TextStyle(fontSize: 13.0)),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        Flex(
          direction: Axis.horizontal,
          children: <Widget>[
            Expanded(
              child: Container(
                padding: EdgeInsets.only(top: 20.0, left: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    _getBulletPoint("2"),
                    Container(
                      width: MediaQuery.of(context).size.width * 0.8,
                      child: Text(
                          "The online payment process will be available 24 hours before the appointment.",
                          overflow: TextOverflow.clip,
                          style: TextStyle(fontSize: 13.0)),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        Container(
          margin: EdgeInsets.fromLTRB(50.0, 20.0, 50.0, 20.0),
          child: Image.asset("assets/images/new-design/payment-method.png"),
        ),
        Container(
          alignment: Alignment.bottomCenter,
          height: MediaQuery.of(context).size.height * 0.32,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              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: () {},
                  child: Text(TranslationBase.of(context).confirm.toUpperCase(),
                      style: TextStyle(fontSize: 18.0)),
                ),
              ),
              ButtonTheme(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10.0),
                ),
                minWidth: MediaQuery.of(context).size.width * 0.7,
                height: 45.0,
                child: RaisedButton(
                  color: new Color(0xFFc5272d),
                  textColor: Colors.white,
                  disabledTextColor: Colors.white,
                  disabledColor: new Color(0xFFbcc2c4),
                  onPressed: () {
                    navigateToHome(context);
                  },
                  child: Text(
                      TranslationBase.of(context).confirmLater.toUpperCase(),
                      style: TextStyle(fontSize: 18.0)),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _getPaymentPendingAppo() {
    return Container();
  }

  Widget _getPayNowAppo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 20.0, bottom: 0.0),
          alignment: Alignment.center,
          child: Text(TranslationBase.of(context).payNowBookSuccess,
              style: TextStyle(
                  fontSize: 20.0,
                  letterSpacing: 0.8,
                  fontWeight: FontWeight.bold)),
        ),
        Container(
          alignment: Alignment.center,
          child: Image.asset("assets/images/new-design/no-wait-queue.png",
              width: 120.0, height: 120.0),
        ),
        Flex(
          direction: Axis.horizontal,
          children: <Widget>[
            Expanded(
              child: Container(
                padding: EdgeInsets.only(left: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    _getBulletPoint("1"),
                    Container(
                      width: MediaQuery.of(context).size.width * 0.8,
                      child: Text(
                          TranslationBase.of(context).payNowBookSuccesstext1,
                          overflow: TextOverflow.fade,
                          style: TextStyle(fontSize: 13.0)),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        Container(
          margin: EdgeInsets.fromLTRB(50.0, 20.0, 50.0, 20.0),
          child: Image.asset("assets/images/new-design/payment-method.png"),
        ),
        Flex(
          direction: Axis.horizontal,
          children: <Widget>[
            Expanded(
              child: Container(
                padding: EdgeInsets.only(top: 0.0, left: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    _getBulletPoint("2"),
                    Container(
                      width: MediaQuery.of(context).size.width * 0.8,
                      child: Text(
                          TranslationBase.of(context).payNowBookSuccesstext2,
                          overflow: TextOverflow.clip,
                          style: TextStyle(fontSize: 13.0)),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        Container(
          alignment: Alignment.bottomCenter,
          height: MediaQuery.of(context).size.height * 0.2,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              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: () {
                    startPaymentProcess();
                  },
                  child: Text(TranslationBase.of(context).payNow.toUpperCase(),
                      style: TextStyle(fontSize: 18.0)),
                ),
              ),
              ButtonTheme(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10.0),
                ),
                minWidth: MediaQuery.of(context).size.width * 0.7,
                height: 45.0,
                child: RaisedButton(
                  color: new Color(0xFFc5272d),
                  textColor: Colors.white,
                  disabledTextColor: Colors.white,
                  disabledColor: new Color(0xFFbcc2c4),
                  onPressed: () {
                    navigateToHome(context);
                  },
                  child: Text(
                      TranslationBase.of(context).payLater.toUpperCase(),
                      style: TextStyle(fontSize: 18.0)),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  startPaymentProcess() {
    navigateToPaymentMethod(context, widget.patientShareResponse);
  }

  Future navigateToPaymentMethod(
      context, PatientShareResponse patientShareResponse) async {
    if (await this.sharedPref.getObject(USER_PROFILE) != null) {
      var data = AuthenticatedUser.fromJson(
          await this.sharedPref.getObject(USER_PROFILE));
      setState(() {
        authUser = data;
      });
    }

    AppoitmentAllHistoryResultList appo = new AppoitmentAllHistoryResultList();
    appo.projectID = widget.patientShareResponse.projectID;
    appo.clinicID = widget.patientShareResponse.clinicID;
    appo.appointmentNo = widget.patientShareResponse.appointmentNo;

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

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

    widget.browser.openPaymentBrowser(
        amount,
        "Appointment check in",
        Utils.getAppointmentTransID(
            appo.projectID, appo.clinicID, appo.appointmentNo),
        appo.projectID.toString(),
        authenticatedUser.emailAddress,
        paymentMethod,
        authenticatedUser,
        widget.browser);
  }

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

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

    MyInAppBrowser.errorURLS.forEach((element) {
      if (url.contains(element)) {
        if (widget.browser.isOpened()) widget.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') {
        createAdvancePayment(res, appo);
      } else {
        AppToast.showErrorToast(message: res['Response_Message']);
      }
    }).catchError((err) {
      print(err);
    }).showProgressBar(text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }

  createAdvancePayment(res, AppoitmentAllHistoryResultList appo) {
    DoctorsListService service = new DoctorsListService();
    String paymentReference = res['Fort_id'].toString();
    service
        .createAdvancePayment(
            appo, res['Amount'], res['Fort_id'], res['PaymentMethod'], context)
        .then((res) {
      print(res['OnlineCheckInAppointments'][0]['AdvanceNumber']);
      addAdvancedNumberRequest(
          res['OnlineCheckInAppointments'][0]['AdvanceNumber'].toString(),
          paymentReference,
          appo.appointmentNo.toString());
    }).catchError((err) {
      print(err);
    }).showProgressBar(text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }
//
//  Future navigateToQR(
//      context, String appoQR, PatientShareResponse patientShareResponse) async {
//    Navigator.push(
//        context,
//        MaterialPageRoute(
//            builder: (context) => QRCode(
//                  patientShareResponse: patientShareResponse,
//                  appoQR: appoQR,
//                ))).then((value) {});
//  }

  addAdvancedNumberRequest(String advanceNumber, String paymentReference,
      String appointmentID) {
    DoctorsListService service = new DoctorsListService();
    service
        .addAdvancedNumberRequest(
            advanceNumber, paymentReference, appointmentID, context)
        .then((res) {
      print(res);
      getAppoQR(context);
    }).catchError((err) {
      print(err);
    }).showProgressBar(text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }

  Widget _getQRAppo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 30.0, bottom: 40.0),
          alignment: Alignment.center,
          child: Text(TranslationBase.of(context).noNeedToWaitInLine,
              style: TextStyle(fontSize: 18.0, letterSpacing: 0.8)),
        ),
        Container(
          alignment: Alignment.center,
          child: Image.asset("assets/images/new-design/device_icon.png",
              width: 120.0, height: 120.0),
        ),
        Flex(
          direction: Axis.horizontal,
          children: <Widget>[
            Expanded(
              child: Container(
                padding: EdgeInsets.only(left: 10.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(top: 15.0),
                      child: Row(
                        children: <Widget>[
                          _getBulletPoint("1"),
                          Container(
                            width: MediaQuery.of(context).size.width * 0.8,
                            child: Text(
                                TranslationBase.of(context).useQRAppoAttend,
                                overflow: TextOverflow.fade,
                                style: TextStyle(fontSize: 13.0)),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 15.0),
                      child: Row(
                        children: <Widget>[
                          _getBulletPoint("2"),
                          Container(
                            width: MediaQuery.of(context).size.width * 0.8,
                            child: Text(
                                TranslationBase.of(context).passQRAppoAttend,
                                overflow: TextOverflow.fade,
                                style: TextStyle(fontSize: 13.0)),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 15.0),
                      child: Row(
                        children: <Widget>[
                          _getBulletPoint("3"),
                          Container(
                            width: MediaQuery.of(context).size.width * 0.8,
                            child: Text(
                                TranslationBase.of(context).sitWaitingQR,
                                overflow: TextOverflow.fade,
                                style: TextStyle(fontSize: 13.0)),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        Container(
          alignment: Alignment.bottomCenter,
          height: MediaQuery.of(context).size.height * 0.18,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              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: () {
//                    navigateToQR(context);
                    getAppoQR(context);
                  },
                  child: Text(TranslationBase.of(context).viewQR.toUpperCase(),
                      style: TextStyle(fontSize: 18.0)),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  _getTextStyling() {
    return TextStyle(fontSize: 14.0, color: Colors.white, letterSpacing: 0.7);
  }

  _getBulletPoint(bulletPoint) {
    return Container(
      margin: EdgeInsets.only(left: 20.0, right: 20.0),
      decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.black),
      width: 20.0,
      height: 20.0,
      child: Center(
        child: Text(bulletPoint,
            style: TextStyle(
              color: Colors.white,
              fontSize: 12.0,
            )),
      ),
    );
  }

  _getHeadingText(text) {
    return Container(
        padding: EdgeInsets.only(bottom: 10.0),
        child: Text(text,
            textAlign: TextAlign.center,
            style: TextStyle(
                fontSize: 26.0,
                fontFamily: 'Open-Sans',
                letterSpacing: 0.5,
                color: Colors.white)));
  }

  Future navigateToHome(context) async {
    Navigator.of(context).pushNamed(HOME);
  }

  getAppoQR(context) {
    DoctorsListService service = new DoctorsListService();
    service
        .generateAppointmentQR(widget.patientShareResponse, context)
        .then((res) {
      print(res);
      navigateToQR(context, res['AppointmentQR']);
    }).catchError((err) {
      print(err);
    }).showProgressBar(text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }

  Future navigateToQR(context, String appoQR) async {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => QRCode(
                  patientShareResponse: widget.patientShareResponse,
                  appoQR: appoQR,
                )));
  }

  _getNormalText(text) {
    return Container(
      margin: EdgeInsets.only(top: 5.0),
      padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
      child: Text(text,
          textAlign: TextAlign.center,
          style: TextStyle(
              fontSize: 12,
              fontFamily: 'Open-Sans',
              letterSpacing: 0.5,
              color: Colors.white)),
    );
  }
}
