import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:mohem_flutter_app/api/dashboard_api_client.dart';
import 'package:mohem_flutter_app/app_state/app_state.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/models/generic_response_model.dart';
import 'package:mohem_flutter_app/models/privilege_list_model.dart';
import 'package:mohem_flutter_app/provider/dashboard_provider_model.dart';
import 'package:mohem_flutter_app/ui/dialogs/success_dialog.dart';
import 'package:mohem_flutter_app/widgets/dialogs/confirm_dialog.dart';
import 'package:mohem_flutter_app/widgets/dialogs/dialogs.dart';
import 'package:mohem_flutter_app/widgets/location/Location.dart';
import 'package:mohem_flutter_app/widgets/nfc/nfc_reader_sheet.dart';
import 'package:mohem_flutter_app/widgets/qr_scanner_dialog.dart';
import 'package:nfc_manager/nfc_manager.dart';
import 'package:wifi_iot/wifi_iot.dart';

class MarkAttendanceWidget extends StatefulWidget {
  DashboardProviderModel model;
  double topPadding;
  bool isFromDashboard;

  MarkAttendanceWidget(this.model, {Key? key, this.topPadding = 0, this.isFromDashboard = false}) : super(key: key);

  @override
  _MarkAttendanceWidgetState createState() {
    return _MarkAttendanceWidgetState();
  }
}

class _MarkAttendanceWidgetState extends State<MarkAttendanceWidget> {
  bool isNfcEnabled = false, isNfcLocationEnabled = false, isQrEnabled = false, isQrLocationEnabled = false, isWifiEnabled = false, isWifiLocationEnabled = false;

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

  void checkAttendanceAvailability() async {
    bool isAvailable = await NfcManager.instance.isAvailable();
    setState(() {
      AppState().privilegeListModel!.forEach((PrivilegeListModel element) {
        if (element.serviceName == "enableNFC") {
          if (isAvailable) if (element.previlege ?? false) isNfcEnabled = true;
        } else if (element.serviceName == "enableQR") {
          if (element.previlege ?? false) isQrEnabled = true;
        } else if (element.serviceName == "enableWIFI") {
          if (element.previlege ?? false) isWifiEnabled = true;
        } else if (element.serviceName!.trim() == "enableLocationNFC") {
          if (element.previlege ?? false) isNfcLocationEnabled = true;
        } else if (element.serviceName == "enableLocationQR") {
          if (element.previlege ?? false) isQrLocationEnabled = true;
        } else if (element.serviceName == "enableLocationWIFI") {
          if (element.previlege ?? false) isWifiLocationEnabled = true;
        }
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    // Stop Session
    NfcManager.instance.stopSession();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 21, right: 21, bottom: 21, top: widget.topPadding),
      decoration: const BoxDecoration(borderRadius: BorderRadius.only(topLeft: Radius.circular(25), topRight: Radius.circular(25)), color: Colors.white),
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          LocaleKeys.markAttendance.tr().toSectionHeading(),
          LocaleKeys.selectMethodOfAttendance.tr().tr().toText11(color: const Color(0xff535353)),
          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>[
              // if (isNfcEnabled)
              attendanceMethod("NFC", "assets/images/nfc.svg", isNfcEnabled, () {
                if (isNfcLocationEnabled) {
                  Location.getCurrentLocation((LatLng? latlng, bool isMocked) {
                    if (isMocked) {
                      markFakeAttendance("NFC", latlng?.latitude.toString() ?? "", latlng?.longitude.toString() ?? "");
                    } else {
                      performNfcAttendance(widget.model, lat: latlng?.latitude.toString() ?? "", lng: latlng?.longitude.toString() ?? "");
                    }
                  }, context);
                } else {
                  performNfcAttendance(widget.model);
                }
              }),
              if (isWifiEnabled)
                attendanceMethod("Wifi", "assets/images/wufu.svg", isWifiEnabled, () {
                  if (isWifiLocationEnabled) {
                    Location.getCurrentLocation((LatLng? latlng, bool isMocked) {
                      if (isMocked) {
                        markFakeAttendance("WIFI", latlng?.latitude.toString() ?? "", latlng?.longitude.toString() ?? "");
                      } else {
                        performWifiAttendance(widget.model, lat: latlng?.latitude.toString() ?? "", lng: latlng?.longitude.toString() ?? "");
                      }
                    }, context);
                  } else {
                    performWifiAttendance(widget.model);
                  }
                  // connectWifi();
                }),
              if (isQrEnabled)
                attendanceMethod("QR", "assets/images/ic_qr.svg", isQrEnabled, () async {
                  if (isQrLocationEnabled) {
                    Location.getCurrentLocation((LatLng? latlng, bool isMocked) {
                      if (isMocked) {
                        markFakeAttendance("QR", latlng?.latitude.toString() ?? "", latlng?.longitude.toString() ?? "");
                      } else {
                        performQrCodeAttendance(widget.model, lat: latlng?.latitude.toString() ?? "", lng: latlng?.longitude.toString() ?? "");
                      }
                    }, context);
                  } else {
                    performQrCodeAttendance(widget.model);
                  }
                  // performQrCodeAttendance(model);
                }),
            ],
          )
        ],
      ),
    );
  }

  Future<void> performNfcAttendance(DashboardProviderModel model, {String lat = "0", String lng = "0"}) async {
    if (Platform.isIOS) {

      Utils.readNFc(onRead: (String nfcId) async {
        Utils.showLoading(context);
        try {
          GenericResponseModel? g = await DashboardApiClient().markAttendance(pointType: 2, nfcValue: nfcId, isGpsRequired: isNfcLocationEnabled, lat: lat, long: lng);
          if (g?.messageStatus != 1) {
            Utils.hideLoading(context);
            showDialog(
              context: context,
              builder: (BuildContext cxt) => ConfirmDialog(
                message: g?.errorEndUserMessage ?? "Unexpected error occurred",
                onTap: () {
                  Navigator.pop(context);
                },
              ),
            );
          } else {
            bool status = await model.fetchAttendanceTracking(context);
            if (Platform.isIOS) await Future.delayed(const Duration(seconds: 3));
            Utils.hideLoading(context);
            showMDialog(
              context,
              backgroundColor: Colors.transparent,
              isDismissable: true,
              child: SuccessDialog(widget.isFromDashboard),
            );
          }
        } catch (ex) {
          Utils.hideLoading(context);
          Utils.handleException(ex, context, null);
        }
      });
    } else {
      showNfcReader(context, onNcfScan: (String? nfcId) async {
        Utils.showLoading(context);
        try {
          GenericResponseModel? g = await DashboardApiClient().markAttendance(pointType: 2, nfcValue: nfcId ?? "", isGpsRequired: isNfcLocationEnabled, lat: lat, long: lng);
          if (g?.messageStatus != 1) {
            Utils.hideLoading(context);
            showDialog(
              context: context,
              builder: (BuildContext cxt) => ConfirmDialog(
                message: g?.errorEndUserMessage ?? "Unexpected error occurred",
                onTap: () {
                  Navigator.pop(context);
                },
              ),
            );
          } else {
            bool status = await model.fetchAttendanceTracking(context);
            Utils.hideLoading(context);
            showMDialog(
              context,
              backgroundColor: Colors.transparent,
              isDismissable: false,
              child: SuccessDialog(widget.isFromDashboard),
            );
          }
        } catch (ex) {
          print(ex);
          Utils.hideLoading(context);
          Utils.handleException(ex, context, (String msg) {
            Utils.confirmDialog(context, msg);
          });
        }
      });
    }
  }

  Future<void> performWifiAttendance(DashboardProviderModel model, {String lat = "0", String lng = "0"}) async {
    Utils.showLoading(context);
    bool isConnected = await WiFiForIoTPlugin.connect(AppState().getMohemmWifiSSID ?? "",
        password: AppState().getMohemmWifiPassword ?? "", joinOnce: Platform.isIOS ? false : true, security: NetworkSecurity.WPA, withInternet: false);

    if (Platform.isIOS) {
      if (await WiFiForIoTPlugin.getSSID() == AppState().getMohemmWifiSSID) {
        isConnected = true;
      } else {
        isConnected = false;
      }
    }

    if (isConnected) {
      // if (Platform.isIOS) {
      //   await closeWifiRequest();
      //   await Future.delayed(Duration(seconds: 6));
      // } else {
      //   await WiFiForIoTPlugin.forceWifiUsage(true);
      // }
      await WiFiForIoTPlugin.forceWifiUsage(true);
      await Future.delayed(const Duration(seconds: 6));
      try {
        GenericResponseModel? g = await DashboardApiClient().markAttendance(pointType: 3, nfcValue: "", isGpsRequired: isWifiLocationEnabled, lat: lat, long: lng);
        bool status = await model.fetchAttendanceTracking(context);
        Utils.hideLoading(context);
        // if (Platform.isAndroid) {
        //   await closeWifiRequest();
        // }

        await closeWifiRequest();
        showMDialog(
          context,
          backgroundColor: Colors.transparent,
          isDismissable: false,
          child: SuccessDialog(widget.isFromDashboard),
        );
      } catch (ex) {
        await closeWifiRequest();
        Utils.hideLoading(context);
        Utils.handleException(ex, context, null);
      }
    } else {
      Utils.hideLoading(context);
      Utils.confirmDialog(context, LocaleKeys.comeNearHMGWifi.tr());
    }
  }

  Future<bool> closeWifiRequest() async {
    if (Platform.isAndroid) {
      await WiFiForIoTPlugin.forceWifiUsage(false);
    }
    return await WiFiForIoTPlugin.disconnect();
  }

  Future<void> performQrCodeAttendance(DashboardProviderModel model, {String lat = "0", String lng = "0"}) async {
    var qrCodeValue = await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (BuildContext context) => QrScannerDialog(),
      ),
    );
    if (qrCodeValue != null) {
      Utils.showLoading(context);
      try {
        GenericResponseModel? g = await DashboardApiClient().markAttendance(pointType: 1, isGpsRequired: isQrLocationEnabled, lat: lat, long: lng, QRValue: qrCodeValue);
        bool status = await model.fetchAttendanceTracking(context);
        Utils.hideLoading(context);
        showMDialog(
          context,
          backgroundColor: Colors.transparent,
          isDismissable: true,
          child: SuccessDialog(widget.isFromDashboard),
        );
      } catch (ex) {
        print(ex);
        Utils.hideLoading(context);
        Utils.handleException(ex, context, null);
      }
    }
  }

  void markFakeAttendance(String sourceName, String lat, String long) async {
    Utils.showLoading(context);
    try {
      await DashboardApiClient().markFakeLocation(sourceName: sourceName, lat: lat, long: long);
      Utils.hideLoading(context);
      Utils.confirmDialog(context, LocaleKeys.fakeLocation.tr());
    } catch (ex) {
      print(ex);
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  Widget attendanceMethod(String title, String image, bool isEnabled, VoidCallback onPress) => Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(15),
          color: isEnabled ? null : Colors.grey.withOpacity(.5),
          gradient: isEnabled
              ? const LinearGradient(
                  transform: GradientRotation(.64),
                  begin: Alignment.topRight,
                  end: Alignment.bottomLeft,
                  colors: [
                    MyColors.gradiantEndColor,
                    MyColors.gradiantStartColor,
                  ],
                )
              : null,
        ),
        clipBehavior: Clip.antiAlias,
        padding: const EdgeInsets.only(left: 10, right: 10, top: 14, bottom: 14),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SvgPicture.asset(image, color: Colors.white, alignment: Alignment.topLeft).expanded,
            title.toText17(isBold: true, color: Colors.white),
          ],
        ),
      ).onPress(
        () {
          if (!isEnabled) return;
          onPress();
        },
      );
}
