import 'package:barcode_scan2/barcode_scan2.dart';
import 'package:hmg_patient_app/core/model/privilege/ProjectDetailListModel.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/pages/BookAppointment/BookConfirm.dart';
import 'package:hmg_patient_app/services/appointment_services/GetDoctorsList.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/date_uitl.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/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_svg/flutter_svg.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

import '../../../uitl/utils.dart';

class WaitingAppointmentVerification extends StatefulWidget {
  const WaitingAppointmentVerification({super.key});

  @override
  State<WaitingAppointmentVerification> createState() => _WaitingAppointmentVerificationState();
}

class _WaitingAppointmentVerificationState extends State<WaitingAppointmentVerification> {
  String selectedVerificationMethod = "QR";

  late ProjectViewModel projectViewModel;
  late LocationUtils locationUtils;
  ProjectDetailListModel projectDetailListModel = ProjectDetailListModel();

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).waitingAppointment,
      isShowAppBar: true,
      isShowDecPage: false,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      backgroundColor: CustomColors.appBackgroudGreyColor,
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              mHeight(11),
              Text(
                TranslationBase.of(context).waitingAppointmentVerificationMethod,
                maxLines: 1,
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Color(0xff2B353E), letterSpacing: -1.04, height: 35 / 24),
              ),
              mHeight(12),
              Container(
                width: MediaQuery.of(context).size.width,
                decoration: containerRadius(Colors.white, 10),
                child: Padding(
                  padding: const EdgeInsets.fromLTRB(16.0, 0.0, 16.0, 0.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      InkWell(
                        onTap: () {
                          setState(() {
                            selectedVerificationMethod = "QR";
                          });
                        },
                        child: Row(
                          children: [
                            Container(
                              width: 20,
                              height: 20,
                              decoration: containerColorRadiusBorderWidth(selectedVerificationMethod == "QR" ? CustomColors.accentColor : Colors.transparent, 100, Colors.grey, 0.5),
                            ),
                            mWidth(6),
                            Container(
                              height: 40.0,
                              width: 40.0,
                              padding: EdgeInsets.all(7.0),
                              child: SvgPicture.asset(
                                "assets/images/new/services/qr_code.svg",
                              ),
                            ),
                            Text(
                              TranslationBase.of(context).pharmaLiveCareScanQR,
                              style: TextStyle(fontSize: 14, color: CustomColors.textDarkColor, fontWeight: FontWeight.w600, letterSpacing: -1.04, height: 35 / 24, overflow: TextOverflow.clip),
                            ),
                          ],
                        ),
                      ),
                      Divider(),
                      InkWell(
                        onTap: () {
                          setState(() {
                            selectedVerificationMethod = "NFC";
                          });
                        },
                        child: Row(
                          children: [
                            Container(
                              width: 20,
                              height: 20,
                              decoration: containerColorRadiusBorderWidth(selectedVerificationMethod == "NFC" ? CustomColors.accentColor : Colors.transparent, 100, Colors.grey, 0.5),
                            ),
                            mWidth(6),
                            Container(
                              height: 40.0,
                              width: 40.0,
                              padding: EdgeInsets.all(7.0),
                              child: SvgPicture.asset(
                                "assets/images/new/services/contactless.svg",
                              ),
                            ),
                            Text(
                              TranslationBase.of(context).scanNFC,
                              style: TextStyle(fontSize: 14, color: CustomColors.textDarkColor, fontWeight: FontWeight.w600, letterSpacing: -1.04, height: 35 / 24, overflow: TextOverflow.clip),
                            ),
                          ],
                        ),
                      ),
                      Divider(),
                      InkWell(
                        onTap: () {
                          setState(() {
                            selectedVerificationMethod = "Location";
                          });
                        },
                        child: Row(
                          children: [
                            Container(
                              width: 20,
                              height: 20,
                              decoration: containerColorRadiusBorderWidth(selectedVerificationMethod == "Location" ? CustomColors.accentColor : Colors.transparent, 100, Colors.grey, 0.5),
                            ),
                            mWidth(6),
                            Container(
                              height: 40.0,
                              width: 40.0,
                              padding: EdgeInsets.all(7.0),
                              child: SvgPicture.asset(
                                "assets/images/new/services/location.svg",
                              ),
                            ),
                            Text(
                              TranslationBase.of(context).checkInViaLocation,
                              style: TextStyle(fontSize: 14, color: CustomColors.textDarkColor, fontWeight: FontWeight.w600, letterSpacing: -1.04, height: 35 / 24, overflow: TextOverflow.clip),
                            ),
                          ],
                        ),
                      ),
                      mHeight(6),
                    ],
                  ),
                ),
              ),
              mHeight(12),
              Container(
                width: MediaQuery.of(context).size.width,
                decoration: containerRadius(Colors.white, 10),
                child: Padding(
                  padding: const EdgeInsets.fromLTRB(16.0, 0.0, 16.0, 0.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      mHeight(12),
                      Text(
                        TranslationBase.of(context).howToUseVerificationMethod,
                        maxLines: 1,
                        style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -1.04, height: 35 / 24),
                      ),
                      mHeight(12),
                      Image.asset(
                        'assets/images/new/NFCCheckIn_QR_gps_HMG.png',
                        fit: BoxFit.fitWidth,
                        width: MediaQuery.of(context).size.width,
                      ),
                      mHeight(12),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      bottomSheet: Container(
        height: 80,
        color: CustomColors.white,
        padding: EdgeInsets.fromLTRB(12.0, 12.0, 12.0, 25.0),
        child: Container(
          child: DefaultButton(
            TranslationBase.of(context).continues,
            () {
              startVerification();
            },
            color: CustomColors.accentColor,
          ),
        ),
      ),
    );
  }

  startVerification() {
    switch (selectedVerificationMethod) {
      case "QR":
        startQRCodeScan();
        break;
      case "NFC":
        startNFCScan();
        break;
      case "Location":
        startLocationCheckIn();
        break;
    }
  }

  checkScannedNFCAndQRCode(String nfcId) {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.checkScannedNFCAndQRCode(nfcId, projectViewModel.waitingAppointmentDoctor!.projectID!).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      projectViewModel.setWaitingAppointmentNFCCode(nfcId);
      if (res["returnValue"] == 1) {
        navigateToBookConfirm(context);
      } else {
        AppToast.showErrorToast(message: "Invalid verification point scanned.");
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  Future navigateToBookConfirm(context) async {
    final DateFormat formatter = DateFormat('yyyy-MM-dd');
    Navigator.push(
      context,
      FadePage(
        page: BookConfirm(
          doctor: projectViewModel.waitingAppointmentDoctor!,
          isLiveCareAppointment: false,
          selectedDate: formatter.format(DateTime.now()),
          selectedTime: TranslationBase.of(context).waitingAppointment,
          initialSlotDuration: 15,
          isWalkinAppointment: true,
        ),
      ),
    );
  }

  startLocationCheckIn() async {
    locationUtils = new LocationUtils(isShowConfirmDialog: true, context: context);
    locationUtils.getCurrentLocation(callBack: (value) {
      projectDetailListModel = Utils.getProjectDetailObj(projectViewModel, projectViewModel.waitingAppointmentProjectID);
      double dist = Utils.distance(value.latitude, value.longitude, double.parse(projectDetailListModel.latitude!), double.parse(projectDetailListModel.longitude!)).ceilToDouble() * 1000;
      projectViewModel.setWaitingAppointmentNFCCode(projectDetailListModel.checkInQrCode!);
      print(dist);
      if (dist <= projectDetailListModel.geofenceRadius!) {
        navigateToBookConfirm(context);
      } else {
        AppToast.showErrorToast(message: TranslationBase.of(context).locationCheckInError);
      }
    });
  }

  startNFCScan() {
    Future.delayed(const Duration(milliseconds: 500), () {
      showNfcReader(context, onNcfScan: (String nfcId) {
        Future.delayed(const Duration(milliseconds: 100), () {
          checkScannedNFCAndQRCode(nfcId);
        });
      }, onCancel: () {
        // Navigator.of(context).pop();
        // locator<GAnalytics>().todoList.to_do_list_nfc_cancel(widget.appointment!);
      });
    });
  }

  startQRCodeScan() async {
    String onlineCheckInQRCode = (await BarcodeScanner.scan().then((value) => value.rawContent));
    if (onlineCheckInQRCode != "") {
      checkScannedNFCAndQRCode(onlineCheckInQRCode);
    } else {}
  }
}
