import 'package:diplomaticquarterapp/core/model/prescriptions/prescription_report_enh.dart';
import 'package:diplomaticquarterapp/core/model/radiology/final_radiology.dart';
import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/models/Appointments/appoDetailsButtons.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/models/AppointmentType.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/models/ArrivedButtons.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/models/AskDocRequestTypeModel.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/models/BookedButtons.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/models/BookedButtonsAllowCheckIn.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/models/ConfirmedButtons.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/models/ConfirmedButtonsAllowCheckIn.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/widgets/PrescriptionReport.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/widgets/askDocDialog.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/widgets/reminder_dialog.dart';
import 'package:diplomaticquarterapp/pages/feedback/feedback_home_page.dart';
import 'package:diplomaticquarterapp/pages/insurance/insurance_approval_screen.dart';
import 'package:diplomaticquarterapp/pages/medical/radiology/radiology_details_page.dart';
import 'package:diplomaticquarterapp/pages/medical/vital_sign/vital_sign_details_screen.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/in_app_browser/InAppBrowser.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:smart_progress_bar/smart_progress_bar.dart';
import 'package:url_launcher/url_launcher.dart';

class AppointmentActions extends StatefulWidget {
  AppoitmentAllHistoryResultList appo;
  TabController tabController;
  final Function enableFooterButton;
  MyInAppBrowser browser;

  AppointmentActions(
      {@required this.appo,
      @required this.tabController,
      @required this.enableFooterButton});

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

class _AppointmentActionsState extends State<AppointmentActions> {
  List<AppoDetailsButton> appoButtonsList = [];

  @override
  void initState() {
    _getAppointmentActionButtons();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    final double itemHeight = ((size.height - kToolbarHeight - 24) * 0.42) / 2;
    final double itemWidth = size.width / 2;

    return Container(
      margin: EdgeInsets.all(5.0),
      child: CustomScrollView(
        primary: false,
        physics: NeverScrollableScrollPhysics(),
        slivers: <Widget>[
          SliverPadding(
            padding: const EdgeInsets.fromLTRB(15, 0, 15, 0),
            sliver: SliverGrid.count(
              crossAxisCount: 2,
              childAspectRatio: (itemWidth / itemHeight),
              children: appoButtonsList
                  .map((e) => GestureDetector(
                        onTap: () {
                          _handleButtonClicks(e);
                        },
                        child: Container(
                          height: 100.0,
                          margin: EdgeInsets.all(9.0),
                          decoration: BoxDecoration(
                              boxShadow: [
                                BoxShadow(
                                    color: Colors.grey[400],
                                    blurRadius: 2.0,
                                    spreadRadius: 0.0)
                              ],
                              borderRadius: BorderRadius.circular(10),
                              color: Colors.white),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisSize: MainAxisSize.min,
                            children: <Widget>[
                              Container(
                                margin:
                                    EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 0.0),
                                child: Text(e.title,
                                    overflow: TextOverflow.clip,
                                    style: TextStyle(
                                        color: new Color(0xFFc5272d),
                                        letterSpacing: 1.0,
                                        fontSize: 20.0)),
                              ),
                              Container(
                                margin:
                                    EdgeInsets.fromLTRB(10.0, 0.0, 10.0, 0.0),
                                child: Text(e.subtitle,
                                    overflow: TextOverflow.clip,
                                    style: TextStyle(
                                        color: Colors.black,
                                        letterSpacing: 1.0,
                                        fontSize: 15.0)),
                              ),
                              Container(
                                alignment: Alignment.bottomRight,
                                margin:
                                    EdgeInsets.fromLTRB(0.0, 10.0, 10.0, 7.0),
                                child: Image.asset(e.icon,
                                    width: 45.0, height: 45.0),
                              ),
                            ],
                          ),
                        ),
                      ))
                  .toList(),
            ),
          ),
        ],
      ),
    );
  }

  _handleButtonClicks(AppoDetailsButton) {
    print(AppoDetailsButton.caller);

    switch (AppoDetailsButton.caller) {
      case "openReschedule":
        widget.tabController.animateTo((widget.tabController.index + 1) % 2);
        setState(() {
          print("Reschedule");
          widget.enableFooterButton();
        });
        break;

      case "onCancelAppointment":
        ConfirmDialog dialog = new ConfirmDialog(
            context: context,
            confirmMessage: TranslationBase.of(context).cancelAppoMsg,
            okText: TranslationBase.of(context).confirm,
            cancelText: TranslationBase.of(context).cancel_nocaps,
            okFunction: () => {cancelAppointment()},
            cancelFunction: () => {});
        dialog.showAlertDialog(context);
        break;

      case "confirmAppointment":
        confirmAppointment();
        break;

      case "navigateToProject":
        openMap(double.parse(widget.appo.latitude),
            double.parse(widget.appo.longitude));
        break;

      case "addReminder":
        showReminderDialog(widget.appo);
        break;

      case "goToTodoList":
        Navigator.of(context).pop();
        break;

      case "askDoc":
        askYourDoc();
        break;

      case "radiology":
        openAppointmentRadiology();
        break;

      case "prescriptions":
        openPrescriptionReport();
        break;

      case "Survey":
        rateAppointment();
        break;

      case "Insurance":
        navigateToInsuranceApprovals(widget.appo.appointmentNo);
        break;

      case "VitalSigns":
        navigateToVitalSigns(widget.appo.appointmentNo, widget.appo.projectID);
        break;

      case "insertComplaint":
        navigateToInsertComplaint();
        break;
    }
  }

  _getAppointmentActionButtons() {
    if (widget.appo != null) {
      if (isConfirmed()) {
        if (widget.appo.isOnlineCheckedIN) {
          _getConfirmedCheckInAppoActionsList();
        } else {
          _getConfirmedAppoActionsList();
        }
      } else {
        print("isConfirmed Null");
      }
      if (isBooked()) {
        if (widget.appo.isOnlineCheckedIN) {
          _getBookedCheckInAppoActionsList();
        } else {
          _getBookedAppoActionsList();
        }
      } else {
        print("isBooked Null");
      }
      if (isArrived()) {
        if (widget.appo.clinicID == 17) {
          _getArrivedInvoiceAppoActionsList();
        } else {
          _getArrivedAppoActionsList();
        }
      } else {
        print("isArrived Null");
      }
    } else {
      print("Appo Null");
    }
  }

  bool isConfirmed() {
    return AppointmentType.isConfirmed(widget.appo);
  }

  bool isArrived() {
    return AppointmentType.isArrived(widget.appo);
  }

  bool isCheckedIn() {
    return widget.appo.isOnlineCheckedIN;
  }

  bool isBooked() {
    return AppointmentType.isBooked(widget.appo);
  }

  Future<List<AppoDetailsButton>> _getBookedAppoActionsList() async {
    print("_getBookedAppoActionsList");
    print(BookedButtons.buttons);
    List<AppoDetailsButton> buttonsList = [];
    for (var i = 0; i < BookedButtons.buttons.length; i++) {
      buttonsList.add(AppoDetailsButton(
        title: BookedButtons.buttons[i]['title'],
        subtitle: BookedButtons.buttons[i]['subtitle'],
        icon: BookedButtons.buttons[i]['icon'],
        caller: BookedButtons.buttons[i]['caller'],
      ));
    }
    setState(() {
      appoButtonsList = buttonsList;
    });
  }

  Future<List<AppoDetailsButton>> _getBookedCheckInAppoActionsList() async {
    print("_getBookedCheckInAppoActionsList");
    print(BookedButtonsAllowCheckIn.buttons);
    List<AppoDetailsButton> buttonsList = [];
    for (var i = 0; i < BookedButtonsAllowCheckIn.buttons.length; i++) {
      buttonsList.add(AppoDetailsButton(
        title: BookedButtonsAllowCheckIn.buttons[i]['title'],
        subtitle: BookedButtonsAllowCheckIn.buttons[i]['subtitle'],
        icon: BookedButtonsAllowCheckIn.buttons[i]['icon'],
        caller: BookedButtonsAllowCheckIn.buttons[i]['caller'],
      ));
    }
    setState(() {
      appoButtonsList = buttonsList;
    });
  }

  Future<List<AppoDetailsButton>> _getConfirmedAppoActionsList() async {
    print("_getConfirmedAppoActionsList");
    print(ConfirmedButtons.buttons);
    List<AppoDetailsButton> buttonsList = [];
    for (var i = 0; i < ConfirmedButtons.buttons.length; i++) {
      buttonsList.add(AppoDetailsButton(
        title: ConfirmedButtons.buttons[i]['title'],
        subtitle: ConfirmedButtons.buttons[i]['subtitle'],
        icon: ConfirmedButtons.buttons[i]['icon'],
        caller: ConfirmedButtons.buttons[i]['caller'],
      ));
    }
    setState(() {
      appoButtonsList = buttonsList;
    });
  }

  Future<List<AppoDetailsButton>> _getConfirmedCheckInAppoActionsList() async {
    print("_getConfirmedAllowCheckInAppoActionsList");
    print(ConfirmedButtonsAllowCheckIn.buttons);
    List<AppoDetailsButton> buttonsList = [];
    for (var i = 0; i < ConfirmedButtonsAllowCheckIn.buttons.length; i++) {
      buttonsList.add(AppoDetailsButton(
        title: ConfirmedButtonsAllowCheckIn.buttons[i]['title'],
        subtitle: ConfirmedButtonsAllowCheckIn.buttons[i]['subtitle'],
        icon: ConfirmedButtonsAllowCheckIn.buttons[i]['icon'],
        caller: ConfirmedButtonsAllowCheckIn.buttons[i]['caller'],
      ));
    }
    setState(() {
      appoButtonsList = buttonsList;
    });
  }

  Future<List<AppoDetailsButton>> _getArrivedAppoActionsList() async {
    print("_getArrivedAppoActionsList");
    print(ArrivedButtons.buttons);
    List<AppoDetailsButton> buttonsList = [];
    for (var i = 0; i < ArrivedButtons.buttons.length; i++) {
      buttonsList.add(AppoDetailsButton(
        title: ArrivedButtons.buttons[i]['title'],
        subtitle: ArrivedButtons.buttons[i]['subtitle'],
        icon: ArrivedButtons.buttons[i]['icon'],
        caller: ArrivedButtons.buttons[i]['caller'],
      ));
    }
    setState(() {
      appoButtonsList = buttonsList;
    });
  }

  Future<List<AppoDetailsButton>> _getArrivedInvoiceAppoActionsList() async {
    print("_getArrivedInvoiceAppoActionsList");
    print(ArrivedButtons.buttons);
    List<AppoDetailsButton> buttonsList = [];
    for (var i = 0; i < ArrivedButtons.buttons.length; i++) {
      buttonsList.add(AppoDetailsButton(
        title: ArrivedButtons.buttons[i]['title'],
        subtitle: ArrivedButtons.buttons[i]['subtitle'],
        icon: ArrivedButtons.buttons[i]['icon'],
        caller: ArrivedButtons.buttons[i]['caller'],
      ));
    }
    setState(() {
      appoButtonsList = buttonsList;
    });
  }

  cancelAppointment() {
    ConfirmDialog.closeAlertDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.cancelAppointment(widget.appo, context).then((res) {
      print(res);
      if (res['MessageStatus'] == 1) {
        AppToast.showSuccessToast(message: res['ErrorEndUserMessage']);
        Navigator.of(context).pop();
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      print(err);
    }).showProgressBar(
        text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }

  openAppointmentRadiology() {
    DoctorsListService service = new DoctorsListService();
    FinalRadiology finalRadiology = new FinalRadiology();
    service
        .getPatientRadOrders(widget.appo.appointmentNo.toString(), context)
        .then((res) {
      print(res['FinalRadiologyList']);
      finalRadiology =
          new FinalRadiology.fromJson(res['FinalRadiologyList'][0]);
      print(finalRadiology.reportData);
      navigateToRadiologyDetails(finalRadiology);
    }).catchError((err) {
      print(err);
      AppToast.showErrorToast(message: err);
    }).showProgressBar(
            text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }

  openPrescriptionReport() {
    List<PrescriptionReportEnh> prescriptionReportEnhList = List();
    DoctorsListService service = new DoctorsListService();
    service.getPatientPrescriptionReports(widget.appo, context).then((res) {
      res['ListPRM'].forEach((report) {
        prescriptionReportEnhList.add(PrescriptionReportEnh.fromJson(report));
      });
      print(prescriptionReportEnhList.length);
      if (prescriptionReportEnhList.length != 0) {
        navigateToMedicinePrescriptionReport(
            prescriptionReportEnhList, res['ListPRM']);
      } else {
        AppToast.showErrorToast(message: "Sorry there is no data");
      }
    }).catchError((err) {
      print(err);
      AppToast.showErrorToast(message: err);
    }).showProgressBar(
        text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }

  Future navigateToMedicinePrescriptionReport(
      List<PrescriptionReportEnh> prescriptionReportEnhList,
      dynamic listPres) async {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => PrescriptionReportPage(
                prescriptionReportEnhList: prescriptionReportEnhList,
                listPres: listPres,
                appo: widget.appo)));
  }

  Future navigateToRadiologyDetails(FinalRadiology finalRadiology) async {
    Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) =>
                    RadiologyDetailsPage(finalRadiology: finalRadiology)))
        .then((value) {});
  }

  static Future<void> openMap(double latitude, double longitude) async {
    String googleUrl =
        'https://www.google.com/maps/search/?api=1&query=$latitude,$longitude';
    if (await canLaunch(googleUrl)) {
      await launch(googleUrl);
    } else {
      throw 'Could not open the map.';
    }
  }

  showReminderDialog(AppoitmentAllHistoryResultList appo) {
    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: ReminderDialog(appo: appo),
            ),
          );
        },
        transitionDuration: Duration(milliseconds: 500),
        barrierDismissible: true,
        barrierLabel: '',
        context: context,
        pageBuilder: (context, animation1, animation2) {});
  }

  askYourDoc() {
    DoctorsListService service = new DoctorsListService();
    service.isAllowedToAskDoctor(widget.appo.doctorID, context).then((res) {
      print(res['PatientDoctorAppointmentResultList']);
      if (res['PatientDoctorAppointmentResultList'].length != 0) {
        getCallRequestType();
      } else {
        AppToast.showErrorToast(
            message: TranslationBase.of(context).askDocNotAllowed);
      }
    }).catchError((err) {
      print(err);
      AppToast.showErrorToast(
          message: err);
    }).showProgressBar(
        text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }

  getCallRequestType() {
    DoctorsListService service = new DoctorsListService();
    service.getCallRequestType(context).then((res) {
      List<AskDocRequestType> requestData = new List<AskDocRequestType>();
      res['ListReqTypes'].forEach((element) {
        requestData.add(new AskDocRequestType.fromJson(element));
      });
      Future.delayed(const Duration(milliseconds: 400), () {
        showAskDocRequestDialog(requestData);
      });
    }).catchError((err) {
      print(err);
    }).showProgressBar(
        text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }

  showAskDocRequestDialog(List<AskDocRequestType> requestData) {
    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: AskDocDialog(requestData: requestData),
                ),
              );
            },
            transitionDuration: Duration(milliseconds: 500),
            barrierDismissible: true,
            barrierLabel: '',
            context: context,
            pageBuilder: (context, animation1, animation2) {})
        .then((value) {
      print("Dialog Closed");
      print(value);
      if (value != null) {
        sendAskDocRequest(value);
      }
    });
  }

  sendAskDocRequest(int requestType) {
    DoctorsListService service = new DoctorsListService();
    service
        .sendAskDocCallRequest(widget.appo, requestType.toString(), context)
        .then((res) {
      if (res['MessageStatus'] == 1) {
        AppToast.showSuccessToast(message: "Request Sent Successfully");
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      print(err);
      AppToast.showErrorToast(message: err);
    }).showProgressBar(
            text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }

  confirmAppointment() {
    DoctorsListService service = new DoctorsListService();
    service
        .confirmAppointment(widget.appo.appointmentNo, widget.appo.clinicID,
            widget.appo.projectID, context)
        .then((res) {
      if (res['MessageStatus'] == 1) {
        AppToast.showSuccessToast(message: res['ErrorEndUserMessage']);
        Navigator.of(context).pop();
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      print(err);
    }).showProgressBar(
            text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }

  navigateToInsuranceApprovals(int appoNo) {
    Navigator.push(
        context, FadePage(page: InsuranceApproval(appointmentNo: appoNo)));
  }

  navigateToVitalSigns(int appoNo, int projectID) {
    Navigator.push(
        context,
        FadePage(
            page: VitalSignDetailsScreen(
                appointmentNo: appoNo, projectID: projectID)));
  }

  navigateToInsertComplaint() {
    Navigator.push(context, FadePage(page: FeedbackHomePage()));
  }

  rateAppointment() {
    widget.browser = new MyInAppBrowser();
    widget.browser.openBrowser('http://hmg.com/SitePages/pso.aspx?p=' +
        widget.appo.projectID.toString() +
        '.' +
        widget.appo.appointmentNo.toString() +
        '&c=1');
  }
}
