import 'package:auto_size_text/auto_size_text.dart';
import 'package:easy_localization/src/public_ext.dart';
import 'package:flutter/material.dart';
import 'package:flutter_countdown_timer/flutter_countdown_timer.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/date_uitl.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.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/provider/dashboard_provider_model.dart';
import 'package:mohem_flutter_app/widgets/circular_step_progress_bar.dart';
import 'package:mohem_flutter_app/widgets/mark_attendance_widget.dart';
import 'package:nfc_manager/nfc_manager.dart';
import 'package:provider/provider.dart';
import 'package:wifi_iot/wifi_iot.dart';

class TodayAttendanceScreen extends StatefulWidget {
  TodayAttendanceScreen({Key? key}) : super(key: key);

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

class _TodayAttendanceScreenState extends State<TodayAttendanceScreen> {
  ValueNotifier<dynamic> result = ValueNotifier(null);
  late DashboardProviderModel data;
  bool isNfcEnabled = false, isNfcLocationEnabled = false, isQrEnabled = false, isQrLocationEnabled = false, isWifiEnabled = false, isWifiLocationEnabled = false;

  @override
  void initState() {
    super.initState();
    checkAttendanceAvailability();
    data = Provider.of<DashboardProviderModel>(context, listen: false);
  }

  void checkAttendanceAvailability() async {
    bool isAvailable = await NfcManager.instance.isAvailable();
    setState(() {
      AppState().privilegeListModel!.forEach((element) {
        print(element.serviceName.toString() + "   " + element.previlege.toString()); // Check availability

        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 Scaffold(
      appBar: AppBar(
        backgroundColor: MyColors.backgroundBlackColor,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
        actions: [
          IconButton(
            onPressed: () {
              data.fetchAttendanceTracking(context);
            },
            icon: Icon(
              Icons.ac_unit,
              color: Colors.white,
            ),
          )
        ],
      ),
      backgroundColor: MyColors.backgroundBlackColor,
      body: Consumer<DashboardProviderModel>(
        builder: (context, model, child) {
          return (model.isAttendanceTrackingLoading
                  ? Center(child: CircularProgressIndicator())
                  : Column(
                      children: [
                        Expanded(
                          flex: 2,
                          child: Container(
                            width: double.infinity,
                            color: MyColors.backgroundBlackColor,
                            padding: EdgeInsets.only(top: 4, left: 21, right: 21, bottom: 21),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                DateUtil.getWeekDayMonthDayYearDateFormatted(DateTime.now(), "en").toText24(isBold: true, color: Colors.white),
                                LocaleKeys.timeLeftToday.tr().toText16(color: Color(0xffACACAC)),
                                Center(
                                  child: AspectRatio(
                                    aspectRatio: 265 / 265,
                                    child: CircularStepProgressBar(
                                      totalSteps: 16 * 4,
                                      currentStep: (model.progress * 100).toInt(),
                                      selectedColor: MyColors.gradiantEndColor,
                                      unselectedColor: MyColors.grey70Color,
                                      child: Center(
                                        child: Padding(
                                          padding: const EdgeInsets.all(21.0),
                                          child: Column(
                                            mainAxisSize: MainAxisSize.min,
                                            children: [
                                              CountdownTimer(
                                                endTime: model.endTime,
                                                widgetBuilder: (context, v) {
                                                  return AutoSizeText(
                                                    getValue(v?.hours) + " : " + getValue(v?.min) + " : " + getValue(v?.sec),
                                                    maxLines: 1,
                                                    style: TextStyle(color: Colors.white, fontSize: 42, letterSpacing: -1.92, fontWeight: FontWeight.bold, height: 1),
                                                  );
                                                },
                                                onEnd: null,
                                                endWidget: "00:00:00".toTextAuto(color: Colors.white, isBold: true, fontSize: 30, letterSpacing: -1.92),
                                                textStyle: TextStyle(color: Colors.white, fontSize: 30, letterSpacing: -1.92, fontWeight: FontWeight.bold, height: 1),
                                              ).center.expanded,
                                              LocaleKeys.shiftTime.tr().tr().toTextAuto(color: MyColors.greyACColor, fontSize: 18, maxLine: 1),
                                              (model.attendanceTracking!.pShtName ?? "00:00:00").toString().toTextAuto(color: Colors.white, isBold: true, fontSize: 26, maxLine: 1),
                                            ],
                                          ),
                                        ),
                                      ),
                                    ),
                                  ).paddingAll(12),
                                ).expanded,
                              ],
                            ),
                          ),
                        ),
                        Center(
                          child: Container(
                            decoration: const BoxDecoration(
                              borderRadius: BorderRadius.only(topLeft: Radius.circular(25), topRight: Radius.circular(25)),
                              gradient: LinearGradient(
                                transform: GradientRotation(.64),
                                begin: Alignment.topRight,
                                end: Alignment.bottomLeft,
                                colors: [
                                  MyColors.gradiantEndColor,
                                  MyColors.gradiantStartColor,
                                ],
                              ),
                            ),
                            child: Column(
                              children: [
                                Container(
                                  //height: 187,
                                  padding: const EdgeInsets.only(left: 21, right: 21, top: 21, bottom: 16),
                                  decoration: const BoxDecoration(
                                    borderRadius: BorderRadius.only(topLeft: Radius.circular(25), topRight: Radius.circular(25)),
                                    gradient: LinearGradient(transform: GradientRotation(.64), begin: Alignment.topRight, end: Alignment.bottomLeft, colors: [
                                      MyColors.gradiantEndColor,
                                      MyColors.gradiantStartColor,
                                    ]),
                                  ),
                                  child: Column(
                                    children: [
                                      Row(
                                        children: [
                                          commonStatusView(LocaleKeys.checkIn.tr(), (model.attendanceTracking!.pSwipeIn) ?? "- - : - -"),
                                          commonStatusView(LocaleKeys.checkOut.tr(), (model.attendanceTracking!.pSwipeOut) ?? "- - : - -")
                                        ],
                                      ),
                                      21.height,
                                      Row(
                                        children: [
                                          commonStatusView(LocaleKeys.lateIn.tr(), (model.attendanceTracking!.pLateInHours) ?? "- - : - -"),
                                          commonStatusView(LocaleKeys.regular.tr(), (model.attendanceTracking!.pScheduledHours) ?? "- - : - -")
                                        ],
                                      ),
                                    ],
                                  ),
                                ), //.expanded,

                                MarkAttendanceWidget(model, topPadding: 21),
                              ],
                            ),
                          ),
                        )
                      ],
                    ))
              .animatedSwither();
        },
      ),
    );
  }

  String getValue(int? v) {
    if (v == null) {
      return "00";
    } else if (v.toString().length == 1) {
      return "0" + v.toString();
    } else {
      return v.toString();
    }
  }

  Future<bool> closeWifiRequest() async {
    await WiFiForIoTPlugin.forceWifiUsage(false);
    bool v = await WiFiForIoTPlugin.disconnect();
    return v;
  }

  Widget commonStatusView(String title, String time) => Expanded(
        child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
          title.toText12(color: Colors.white.withOpacity(.69)),
          time.toText22(color: Colors.white, isBold: true),
        ]),
      );
}
