import 'package:barcode_scan2/barcode_scan2.dart';
import 'package:hmg_patient_app/core/model/ImagesInfo.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/pages/ErService/EROnlineCheckIn/EROnlineCheckInBookAppointment.dart';
import 'package:hmg_patient_app/pages/ErService/EROnlineCheckIn/EROnlineCheckInNFCQRCLocation.dart';
import 'package:hmg_patient_app/pages/ErService/EROnlineCheckIn/EROnlineCheckInPaymentDetails.dart';
import 'package:hmg_patient_app/pages/landing/landing_page.dart';
import 'package:hmg_patient_app/services/appointment_services/GetDoctorsList.dart';
import 'package:hmg_patient_app/services/clinic_services/get_clinic_service.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/location_util.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/bottom_options/bottom_sheet.dart';
import 'package:hmg_patient_app/widgets/buttons/defaultButton.dart';
import 'package:hmg_patient_app/widgets/nfc/nfc_reader_sheet.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:hmg_patient_app/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nfc_kit/flutter_nfc_kit.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';

class EROnlineCheckInHomePage extends StatefulWidget {
  const EROnlineCheckInHomePage();

  @override
  State<EROnlineCheckInHomePage> createState() => _EROnlineCheckInHomePageState();
}

class _EROnlineCheckInHomePageState extends State<EROnlineCheckInHomePage> with SingleTickerProviderStateMixin {
  late ProjectViewModel projectViewModel;
  bool _supportsNFC = false;
  bool isPatientArrived = false;

  late LocationUtils locationUtils;

  @override
  void initState() {
    locationUtils = new LocationUtils(isShowConfirmDialog: true, context: context);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // checkIfPatientHasArrived();
      if (projectViewModel.isLogin) checkPatientERAdvanceBalance();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    FlutterNfcKit.nfcAvailability.then((value) {
      _supportsNFC = (value == NFCAvailability.available);
    });
    return AppScaffold(
      isShowAppBar: true,
      appBarTitle: TranslationBase.of(context).emergency + " ${TranslationBase.of(context).checkinOptions}",
      isShowDecPage: true,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      description: TranslationBase.of(context).HHCNotAuthMsg,
      imagesInfo: [ImagesInfo(imageAr: 'https://hmgwebservices.com/Images/MobileApp/HHC/ar/0.png', imageEn: 'https://hmgwebservices.com/Images/MobileApp/HHC/en/0.png')],
      backgroundColor: Color(0xffF8F8F8),
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(topLeft: Radius.circular(10), topRight: Radius.circular(10), bottomLeft: Radius.circular(10), bottomRight: Radius.circular(10)),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.1),
                      spreadRadius: 5,
                      blurRadius: 7,
                      offset: Offset(0, 3), // changes position of shadow
                    ),
                  ],
                ),
                child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Icon(
                        Icons.check_circle,
                        size: 50,
                        color: CustomColors.green,
                      ),
                      mHeight(6),
                      Text(
                        TranslationBase.of(context).whatIsOnlineCheckIn,
                        maxLines: 1,
                        style: TextStyle(
                            fontSize: 20, fontFamily: (projectViewModel.isArabic ? 'Cairo' : 'Poppins'), fontWeight: FontWeight.w700, color: Color(0xff2B353E), letterSpacing: -1.44, height: 35 / 24),
                      ),
                      mHeight(12),
                      Text(
                        TranslationBase.of(context).EROnlineCheckInDesc1,
                        style: TextStyle(fontSize: 13, fontFamily: (projectViewModel.isArabic ? 'Cairo' : 'Poppins'), fontWeight: FontWeight.w700, color: CustomColors.textDarkColor, letterSpacing: -1.44, height: 35 / 24),
                      ),
                      mHeight(16),
                      // Text(
                      //   TranslationBase.of(context).EROnlineCheckInHow,
                      //   maxLines: 1,
                      //   style: TextStyle(
                      //       fontSize: 20, fontFamily: (projectViewModel.isArabic ? 'Cairo' : 'Poppins'), fontWeight: FontWeight.w700, color: Color(0xff2B353E), letterSpacing: -1.44, height: 35 / 24),
                      // ),
                      // Text(
                      //   "Online check-in lets patients fill out forms, share insurance details, and book appointments online, making their visit smoother and quicker.",
                      //   style: TextStyle(fontSize: 14, color: CustomColors.textDarkColor, letterSpacing: -1.44, height: 35 / 24),
                      // ),
                    ],
                  ),
                ),
              ),
              mHeight(24),
              Container(
                width: double.infinity,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(topLeft: Radius.circular(10), topRight: Radius.circular(10), bottomLeft: Radius.circular(10), bottomRight: Radius.circular(10)),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.1),
                      spreadRadius: 5,
                      blurRadius: 7,
                      offset: Offset(0, 3), // changes position of shadow
                    ),
                  ],
                ),
                child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Container(
                            width: 35,
                            height: 35,
                            decoration: BoxDecoration(
                              color: CustomColors.green,
                              borderRadius: BorderRadius.circular(50),
                            ),
                            child: Center(
                              child: Text(
                                "1",
                                style: TextStyle(fontSize: 22, fontWeight: FontWeight.w700, color: CustomColors.white, letterSpacing: -1.44, height: 35 / 24),
                              ),
                            ),
                          ),
                          mWidth(12),
                          SvgPicture.asset(
                            "assets/images/new/tap.svg",
                            width: 35,
                            height: 35,
                          ),
                        ],
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 50, right: 50),
                        child: Text(
                          TranslationBase.of(context).EROnlineCheckInTapOn,
                          maxLines: 1,
                          style: TextStyle(
                              fontSize: 20,
                              fontFamily: (projectViewModel.isArabic ? 'Cairo' : 'Poppins'),
                              fontWeight: FontWeight.w700,
                              color: Color(0xff2B353E),
                              letterSpacing: -1.44,
                              height: 35 / 24),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 50, right: 50),
                        child: Text(
                          TranslationBase.of(context).EROnlineCheckInTapOnCheckIn,
                          style: TextStyle(fontSize: 13, fontFamily: (projectViewModel.isArabic ? 'Cairo' : 'Poppins'), fontWeight: FontWeight.w600, color: CustomColors.textDarkColor, letterSpacing: -1.44, height: 35 / 24),
                        ),
                      ),
                      mHeight(16),
                      Row(
                        children: [
                          Container(
                            width: 35,
                            height: 35,
                            decoration: BoxDecoration(
                              color: CustomColors.green,
                              borderRadius: BorderRadius.circular(50),
                            ),
                            child: Center(
                              child: Text(
                                "2",
                                style: TextStyle(fontSize: 22, fontWeight: FontWeight.w700, color: CustomColors.white, letterSpacing: -1.44, height: 35 / 24),
                              ),
                            ),
                          ),
                          mWidth(12),
                          SvgPicture.asset(
                            "assets/images/new/NFC_Hold.svg",
                            width: 35,
                            height: 35,
                          ),
                        ],
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 50, right: 50),
                        child: Text(
                          TranslationBase.of(context).EROnlineCheckInHoldPhone,
                          maxLines: 1,
                          style: TextStyle(
                              fontSize: 20,
                              fontFamily: (projectViewModel.isArabic ? 'Cairo' : 'Poppins'),
                              fontWeight: FontWeight.w700,
                              color: Color(0xff2B353E),
                              letterSpacing: -1.44,
                              height: 35 / 24),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 50, right: 50),
                        child: Text(
                          TranslationBase.of(context).EROnlineCheckInHoldPhoneInstruction,
                          style: TextStyle(fontSize: 13, fontFamily: (projectViewModel.isArabic ? 'Cairo' : 'Poppins'), fontWeight: FontWeight.w600, color: CustomColors.textDarkColor, letterSpacing: -1.44, height: 35 / 24),
                        ),
                      ),
                      mHeight(16),
                      Row(
                        children: [
                          Container(
                            width: 35,
                            height: 35,
                            decoration: BoxDecoration(
                              color: CustomColors.green,
                              borderRadius: BorderRadius.circular(50),
                            ),
                            child: Center(
                              child: Text(
                                "3",
                                style: TextStyle(fontSize: 22,  fontWeight: FontWeight.w700, color: CustomColors.white, letterSpacing: -1.44, height: 35 / 24),
                              ),
                            ),
                          ),
                          mWidth(12),
                          SvgPicture.asset(
                            "assets/images/new/hourglass.svg",
                            width: 35,
                            height: 35,
                          ),
                        ],
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 50, right: 50),
                        child: Text(
                          TranslationBase.of(context).EROnlineCheckInWaitTurn,
                          maxLines: 1,
                          style: TextStyle(
                              fontSize: 20,
                              fontFamily: (projectViewModel.isArabic ? 'Cairo' : 'Poppins'),
                              fontWeight: FontWeight.w700,
                              color: Color(0xff2B353E),
                              letterSpacing: -1.44,
                              height: 35 / 24),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 50, right: 50),
                        child: Text(
                          TranslationBase.of(context).EROnlineCheckInWaitTurnInstruction,
                          style: TextStyle(fontSize: 13, color: CustomColors.textDarkColor, fontWeight: FontWeight.w600, fontFamily: (projectViewModel.isArabic ? 'Cairo' : 'Poppins'), letterSpacing: -1.44, height: 35 / 24),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      bottomSheet: Container(
        height: projectViewModel.isLogin ? 80 : 1,
        color: CustomColors.white,
        padding: EdgeInsets.fromLTRB(12.0, 12.0, 12.0, 25.0),
        child: isPatientArrived
            ? Container(
                child: DefaultButton(
                  TranslationBase.of(context).arrived,
                  () {
                    // showMyBottomSheet(context,
                    //     callBackFunc: () {},
                    //     child: Padding(
                    //       padding: const EdgeInsets.all(21.0),
                    //       child: Column(
                    //         children: [
                    //           Text(TranslationBase.of(context).scanQRHospital,
                    //               style: TextStyle(
                    //                 fontSize: 20,
                    //                 fontWeight: FontWeight.w600,
                    //                 letterSpacing: -0.48,
                    //               )),
                    //           mHeight(21),
                    //           GridView(
                    //             physics: const NeverScrollableScrollPhysics(),
                    //             shrinkWrap: true,
                    //             gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    //                 crossAxisCount: (MediaQuery.of(context).size.width < 550) ? 3 : 5, childAspectRatio: 1 / 1, crossAxisSpacing: 8, mainAxisSpacing: 12),
                    //             children: [
                    //               attendanceMethod(TranslationBase.of(context).scanNFC, "assets/images/nfc/contactless.svg", true, () {
                    //                 if (_supportsNFC) {
                    //                   Future.delayed(const Duration(milliseconds: 500), () {
                    //                     showNfcReader(context, onNcfScan: (String nfcId) {
                    //                       Future.delayed(const Duration(milliseconds: 100), () {
                    //                         print(nfcId);
                    //                         getProjectIDFromNFC(nfcId, true);
                    //                         // Navigator.push(context, FadePage(page: EROnlineCheckInPaymentDetails()));
                    //                       });
                    //                     }, onCancel: () {
                    //                       Navigator.of(context).pop();
                    //                     });
                    //                   });
                    //                 } else {
                    //                   //NFCNotSupported
                    //                   AppToast.showErrorToast(message: TranslationBase.of(context).NFCNotSupported);
                    //                 }
                    //               }),
                    //               attendanceMethod(TranslationBase.of(context).pharmaLiveCareScanQR, "assets/images/new/services/qr_code.svg", true, () async {
                    //                 String onlineCheckInQRCode = (await BarcodeScanner.scan().then((value) => value.rawContent));
                    //                 if (onlineCheckInQRCode != "") {
                    //                   print(onlineCheckInQRCode);
                    //                   getProjectIDFromNFC(onlineCheckInQRCode, true);
                    //                   // sendNfcCheckInRequest(onlineCheckInQRCode, 2);
                    //                 } else {}
                    //               }),
                    //               attendanceMethod(TranslationBase.of(context).checkInViaLocation, "assets/images/new/services/location.svg", true, () {})
                    //             ],
                    //           ),
                    //         ],
                    //       ),
                    //     ));

                    // Navigator.push(context, FadePage(page: EROnlineCheckInNFCQRLocation(projectID: 15))).then((value) {});

                    if (_supportsNFC) {
                      Future.delayed(const Duration(milliseconds: 500), () {
                        showNfcReader(context, onNcfScan: (String nfcId) {
                          Future.delayed(const Duration(milliseconds: 100), () {
                            print(nfcId);
                            getProjectIDFromNFC(nfcId, true);
                            // Navigator.push(context, FadePage(page: EROnlineCheckInPaymentDetails()));
                          });
                        }, onCancel: () {
                          Navigator.of(context).pop();
                        });
                      });
                    } else {
                      //NFCNotSupported
                      AppToast.showErrorToast(message: TranslationBase.of(context).NFCNotSupported);
                    }
                  },
                  color: CustomColors.accentColor,
                ),
              )
            : Row(
                children: [
                  // Expanded(
                  //   flex: 1,
                  //   child: DefaultButton(
                  //     TranslationBase.of(context).checkinOptions,
                  //     () {
                  //       // Navigator.push(context, FadePage(page: EROnlineCheckInNFCQRLocation(projectID: 15))).then((value) {});
                  //
                  //       if (_supportsNFC) {
                  //         Future.delayed(const Duration(milliseconds: 500), () {
                  //           showNfcReader(context, onNcfScan: (String nfcId) {
                  //             Future.delayed(const Duration(milliseconds: 100), () {
                  //               print(nfcId);
                  //               getProjectIDFromNFC(nfcId, false);
                  //             });
                  //           }, onCancel: () {
                  //             Navigator.of(context).pop();
                  //           });
                  //         });
                  //       } else {
                  //         //NFCNotSupported
                  //         AppToast.showErrorToast(message: TranslationBase.of(context).NFCNotSupported, localContext: context);
                  //       }
                  //     },
                  //     color: CustomColors.green,
                  //   ),
                  // ),
                  // mWidth(12),
                  Expanded(
                    flex: 1,
                    child: DefaultButton(
                      TranslationBase.of(context).bookAppo,
                      () {
                        Navigator.push(context, FadePage(page: EROnlineCheckInBookAppointment()));
                      },
                      color: CustomColors.accentColor,
                    ),
                  ),
                ],
              ),
      ),
    );
  }

  void getProjectIDFromNFC(String nfcID, bool isArrived) {
    GifLoaderDialogUtils.showMyDialog(context);
    ClinicListService ancillaryOrdersService = new ClinicListService();
    ancillaryOrdersService.getProjectIDFromNFC(nfcID).then((response) {
      if (response["GetProjectByNFC"].length != 0) {
        print(response["GetProjectByNFC"]);
        int projectID = response['GetProjectByNFC'][0]["ProjectID"];
        String projectName = response['GetProjectByNFC'][0]["ProjectName"];
        GifLoaderDialogUtils.hideDialog(context);
        if (isArrived) {
          autoGenerateInvoiceER(projectID);
        } else {
          Navigator.push(
            context,
            FadePage(
              page: EROnlineCheckInPaymentDetails(
                projectID: projectID,
                isERBookAppointment: false,
                projectName: projectName,
              ),
            ),
          );
        }
      } else {
        AppToast.showErrorToast(message: "Invalid NFC Card Scanned.");
      }
    }).catchError((err) {
      AppToast.showErrorToast(message: err.toString());
      GifLoaderDialogUtils.hideDialog(context);
    });
  }

  autoGenerateInvoiceER(int projectID) {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.autoGenerateInvoiceERClinic(projectID, 4, null, null, null, null, null, null, true).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      _showMyDialog(TranslationBase.of(context).ERCheckInSuccess, context);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  Future<void> _showMyDialog(String message, BuildContext context) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: true, // user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Alert'),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Text(message),
              ],
            ),
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('OK'),
              onPressed: () {
                Navigator.of(context).pop();
                Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) => LandingPage()), (Route<dynamic> r) => false);
              },
            ),
          ],
        );
      },
    );
  }

  void checkIfPatientHasArrived() {
    GifLoaderDialogUtils.showMyDialog(context);
    ClinicListService ancillaryOrdersService = new ClinicListService();
    ancillaryOrdersService.checkIfPatientHasArrived(15, 10).then((response) {
      print(response["IsPatientArrivedResponse"]);
      isPatientArrived = response['IsPatientArrivedResponse']["IsPatientArrived"];
      GifLoaderDialogUtils.hideDialog(context);
      // erOnlineCheckInPaymentDetailsResponse = EROnlineCheckInPaymentDetailsResponse.fromJson(response["ResponsePatientShare"]);
      setState(() {});
    }).catchError((err) {
      AppToast.showErrorToast(message: err.toString());
      GifLoaderDialogUtils.hideDialog(context);
    });
  }

  Widget markCheckInWidget() {
    return GridView(
      physics: const NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      padding: const EdgeInsets.only(bottom: 0, top: 21),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: (MediaQuery.of(context).size.width < 550) ? 3 : 5, childAspectRatio: 1 / 1, crossAxisSpacing: 8, mainAxisSpacing: 8),
      children: [],
    );
  }

  Widget attendanceMethod(String title, String image, bool isEnabled, VoidCallback onPress) => InkWell(
        onTap: () {
          Navigator.pop(context);
          onPress();
        },
        child: Container(
          decoration: containerColorRadiusBorderWidth(Colors.white, 15, CustomColors.darkGreyColor, 1),
          clipBehavior: Clip.antiAlias,
          padding: const EdgeInsets.only(left: 10, right: 10, top: 14, bottom: 14),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(child: SvgPicture.asset(image, color: Colors.black, alignment: Alignment.topLeft)),
              Text(
                title,
                style: TextStyle(color: Colors.black, fontSize: 14, letterSpacing: -0.68, fontWeight: FontWeight.bold),
              ),
              // title.toText17(isBold: true, color: Colors.white),
            ],
          ),
        ),
      );

  // .onPress(
  //   () {
  //     if (!isEnabled) return;
  //     onPress();
  //   },
  // );

  void checkPatientERAdvanceBalance() {
    locationUtils.getCurrentLocation();
    GifLoaderDialogUtils.showMyDialog(context);
    ClinicListService ancillaryOrdersService = new ClinicListService();
    ancillaryOrdersService.checkPatientERAdvanceBalance(10).then((response) {
      print(response["BalanceAmount"]);
      isPatientArrived = response['BalanceAmount'] > 0;
      GifLoaderDialogUtils.hideDialog(context);
      setState(() {});
    }).catchError((err) {
      AppToast.showErrorToast(message: err.toString());
      GifLoaderDialogUtils.hideDialog(context);
    });
  }
}
