import 'dart:async';

// import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:excelso_attendance/api/api.dart';
import 'package:excelso_attendance/helper/arguments/route_args.dart';
import 'package:excelso_attendance/helper/component/button.dart';
import 'package:excelso_attendance/helper/component/text_field.dart';
// import 'package:excelso_attendance/helper/component/text_field.dart';
import 'package:excelso_attendance/helper/global_function/date_time.dart';
import 'package:excelso_attendance/helper/modal_dialog.dart';
import 'package:excelso_attendance/helper/pref.dart';
import 'package:excelso_attendance/helper/widget_responsive.dart';
import 'package:excelso_attendance/models/branch.dart';
import 'package:excelso_attendance/models/profile.dart';
import 'package:excelso_attendance/models/shift.dart';
import 'package:excelso_attendance/resource/assets.dart';
import 'package:excelso_attendance/resource/colors.dart';
import 'package:excelso_attendance/resource/constanta_string.dart';
import 'package:excelso_attendance/resource/font.dart';
import 'package:excelso_attendance/resource/routes.dart';
import 'package:excelso_attendance/resource/size.dart';
import 'package:excelso_attendance/resource/strings.dart';
import 'package:excelso_attendance/resource/style.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class HomeView extends StatelessWidget {
  const HomeView(
      {super.key, required this.nearestBranch, required this.shiftList});

  final List<BranchModel> nearestBranch;
  final List<ShiftModel> shiftList;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorManager.backgroundColor,
      body: ScreenResponsive(
        widget: BodyWidget(
          nearestBranch: nearestBranch,
          shiftList: shiftList,
        ),
        widthScreen: MediaQuery.of(context).size.width,
      ),
    );
  }
}

class BodyWidget extends StatefulWidget {
  const BodyWidget({
    super.key,
    required this.nearestBranch,
    required this.shiftList,
  });

  final List<BranchModel> nearestBranch;
  final List<ShiftModel> shiftList;

  @override
  State<BodyWidget> createState() => _BodyWidgetState();
}

class _BodyWidgetState extends State<BodyWidget> {
  final TextEditingController nikController = TextEditingController();
  int selectedOutlet = 0;

  // String nikUser =
  //     (getListAbsentUser().isEmpty) ? "" : getListAbsentUser().last;
  String nikUser = "";
  TextEditingController? textEditingController;

  List<String> dataUserAbsent = getListAbsentUser();

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              padding: EdgeInsets.only(
                top: AppPadding.safeAreaTop(context) + 10,
                bottom: 20,
              ),
              decoration: BoxDecoration(
                color: ColorManager.primary,
                borderRadius: const BorderRadius.only(
                  bottomLeft: Radius.circular(20),
                  bottomRight: Radius.circular(20),
                ),
              ),
              child: Center(
                child: (ConstantString.logoUrlHome == "")
                    ? const Image(
                        width: 36,
                        height: 36,
                        image: AssetImage(
                          "",
                        ),
                      )
                    : Image(
                        width: 36,
                        height: 36,
                        image: NetworkImage(
                          ConstantString.logoUrlHome,
                        ),
                      ),
              ),
            )
          ],
        ),
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  margin: EdgeInsets.only(
                    top: AppMargin.m16,
                  ),
                  child: Text(
                    "Attendance",
                    style: getSemiBoldStyle(
                      color: Colors.black,
                      fontSize: 20,
                      fontFamily: FontConstants.montserrat,
                    ),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(
                    top: AppMargin.m16,
                    left: AppMargin.m20,
                    right: AppMargin.m20,
                  ),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20),
                    color: ColorManager.primary,
                  ),
                  child: Container(
                    width: double.infinity,
                    padding: const EdgeInsets.symmetric(
                      vertical: 20,
                      horizontal: 20,
                    ),
                    child: const TimerWidget(),
                  ),
                ),
                SelectOutlet(
                  nearestBranch: widget.nearestBranch,
                  onSelected: ((int val) {
                    selectedOutlet = val;
                  }),
                ),
                Container(
                  margin: EdgeInsets.only(
                    top: AppMargin.m16,
                    left: AppMargin.m20,
                    right: AppMargin.m20,
                  ),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(
                      width: 0.2,
                      color: Colors.grey,
                    ),
                    color: ColorManager.backgroundColor,
                    // boxShadow: [
                    //   BoxShadow(
                    //     color: Colors.grey.withOpacity(0.3),
                    //     blurRadius: 2,
                    //     offset: const Offset(5, 5),
                    //   ),
                    // ],
                  ),
                  child: Container(
                    width: double.infinity,
                    padding: EdgeInsets.all(
                      AppPadding.p15,
                    ),
                    // child: InputTextField(
                    //   controller: nikController,
                    //   labelText: "NIK",
                    //   borderSideActive: true,
                    //   hintText: "NIK",
                    // ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // Container(
                        //   margin: EdgeInsets.only(
                        //     bottom: AppMargin.m12,
                        //   ),
                        //   child: Text(
                        //     "NIK",
                        //     style: getSemiBoldStyle(
                        //       color: Colors.black,
                        //       fontSize: 16,
                        //     ),
                        //   ),
                        // ),
                        InputTextField(
                          controller: nikController,
                          labelText: "NIK",
                          borderSideActive: true,
                          hintText: "NIK",
                        )
                        // Autocomplete(
                        //   optionsBuilder: (TextEditingValue textEditingValue) {
                        //     if (textEditingValue.text.isEmpty) {
                        //       return const Iterable<String>.empty();
                        //     } else {
                        //       return dataUserAbsent.where(
                        //         (data) => data.toLowerCase().contains(
                        //             textEditingValue.text.toLowerCase()),
                        //       );
                        //     }
                        //   },
                        //   onSelected: ((selected) {
                        //     setState(() {
                        //       nikUser = selected;
                        //     });
                        //   }),
                        //   // initialValue: TextEditingValue(
                        //   //   text: (getListAbsentUser().isEmpty)
                        //   //       ? ""
                        //   //       : getListAbsentUser().last,
                        //   // ),
                        //   optionsViewBuilder: (c, onSelected, options) {
                        //     List<String> listNik = options.toList();

                        //     return Container(
                        //       margin: const EdgeInsets.only(
                        //         right: 70,
                        //       ),
                        //       decoration: BoxDecoration(
                        //           borderRadius: BorderRadius.circular(5),
                        //           color: ColorManager.backgroundColor,
                        //           border: Border.all(
                        //             width: 0.2,
                        //             color: Colors.grey,
                        //           ),
                        //           boxShadow: [
                        //             BoxShadow(
                        //               color: Colors.grey.withOpacity(0.3),
                        //               blurRadius: 2,
                        //               offset: const Offset(5, 5),
                        //             ),
                        //           ]),
                        //       child: ListView.builder(
                        //         padding: EdgeInsets.zero,
                        //         itemCount: listNik.length,
                        //         itemBuilder: ((context, index) {
                        //           return GestureDetector(
                        //             onTap: () {
                        //               onSelected(listNik[index]);
                        //             },
                        //             child: Container(
                        //               margin: const EdgeInsets.symmetric(
                        //                   horizontal: 6, vertical: 3),
                        //               padding: EdgeInsets.symmetric(
                        //                 horizontal: AppPadding.p10,
                        //                 vertical: AppPadding.p14,
                        //               ),
                        //               decoration: BoxDecoration(
                        //                 border: (index + 1 != listNik.length)
                        //                     ? Border(
                        //                         bottom: BorderSide(
                        //                           width: 0.5,
                        //                           color: ColorManager.grey
                        //                               .withOpacity(0.8),
                        //                         ),
                        //                       )
                        //                     : null,
                        //               ),
                        //               child: Text(
                        //                 listNik[index],
                        //                 style: getRegularStyle(
                        //                   color: Colors.black,
                        //                   fontSize: 20,
                        //                   fontFamily: FontConstants.poppins,
                        //                 ),
                        //                 maxLines: 2,
                        //                 overflow: TextOverflow.ellipsis,
                        //               ),
                        //             ),
                        //           );
                        //         }),
                        //       ),
                        //     );
                        //   },
                        //   fieldViewBuilder:
                        //       (c, controller, focusNode, onEditingComplete) {
                        //     textEditingController = controller;
                        //     return TextField(
                        //       onChanged: (teks) {
                        //         setState(() {
                        //           nikUser = teks;
                        //         });
                        //       },
                        //       controller: textEditingController,
                        //       focusNode: focusNode,
                        //       onEditingComplete: () {
                        //         setState(() {
                        //           if (focusNode.hasFocus) {
                        //             focusNode.unfocus();
                        //           }
                        //         });
                        //       },
                        //       decoration: InputDecoration(
                        //         hintText: "NIK",
                        //         hintStyle: getRegularStyle(
                        //           color: Colors.grey,
                        //         ),
                        //         enabledBorder: OutlineInputBorder(
                        //           borderSide: BorderSide(
                        //             width: 0.4,
                        //             color: ColorManager.grey,
                        //           ),
                        //           borderRadius: BorderRadius.circular(5),
                        //         ),
                        //         focusedBorder: OutlineInputBorder(
                        //           borderSide: BorderSide(
                        //               width: 0.4, color: ColorManager.grey),
                        //           borderRadius: BorderRadius.circular(5),
                        //         ),
                        //         disabledBorder: OutlineInputBorder(
                        //           borderSide: BorderSide(
                        //               width: 0.4, color: ColorManager.grey),
                        //           borderRadius: BorderRadius.circular(5),
                        //         ),
                        //         suffixIcon:
                        //             (textEditingController!.text.isNotEmpty)
                        //                 ? IconButton(
                        //                     onPressed: () {
                        //                       setState(() {
                        //                         textEditingController!.clear();
                        //                         nikUser = "";
                        //                       });
                        //                     },
                        //                     icon: const Icon(
                        //                       Icons.dangerous,
                        //                       color: Colors.grey,
                        //                     ),
                        //                   )
                        //                 : null,
                        //       ),
                        //     );
                        //   },
                        // ),
                      ],
                    ),
                  ),
                ),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: AppPadding.p20),
                  margin: EdgeInsets.only(
                    top: AppMargin.m16,
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: CustomButton(
                          text: "Masuk",
                          onTap: () {
                            if (nikController.text.isEmpty) {
                              EasyLoading.showToast(
                                "Silakan isi NIK terlebih dahulu",
                              );
                            } else {
                              showModalBottomSheet(
                                  backgroundColor: ColorManager.backgroundColor,
                                  isScrollControlled: true,
                                  context: context,
                                  builder: (c) {
                                    return WidgetSelectShift(
                                      shiftList: widget.shiftList,
                                      branchModel:
                                          widget.nearestBranch[selectedOutlet],
                                      nik: nikController.text,
                                    );
                                  });
                            }
                          },
                        ),
                      ),
                      SizedBox(
                        width: AppMargin.m20,
                      ),
                      Expanded(
                        child: CustomButton(
                          text: "Keluar",
                          onTap: () async {
                            if (nikController.text.isEmpty) {
                              EasyLoading.showToast(
                                "Silakan isi NIK terlebih dahulu",
                              );
                            } else {
                              await EasyLoading.show(
                                status: Strings.pleaseWait,
                                maskType: EasyLoadingMaskType.none,
                              );
                              Api.getUserProfile(
                                widget.nearestBranch[selectedOutlet].id,
                                nikController.text,
                              ).then((apiResponse) {
                                EasyLoading.dismiss();
                                if (apiResponse.error) {
                                  modalDialogGlobal(
                                      context: context,
                                      size: MediaQuery.of(context).size,
                                      title: "Gagal",
                                      contentBody: apiResponse.msg,
                                      buttonText: "Ok",
                                      tapButtonOk: () {
                                        Navigator.pop(context);
                                      });
                                } else {
                                  ProfileModel profileUser =
                                      apiResponse.data as ProfileModel;

                                  if (profileUser.attendanceIn == false) {
                                    modalDialogGlobal(
                                        context: context,
                                        size: MediaQuery.of(context).size,
                                        title: "Gagal",
                                        contentBody: Strings.outButNotIn,
                                        buttonText: "Ok",
                                        tapButtonOk: () {
                                          Navigator.pop(context);
                                        });
                                    return;
                                  }
                                  if (profileUser.attendanceOut) {
                                    modalDialogGlobal(
                                      context: context,
                                      size: MediaQuery.of(context).size,
                                      title: "Peringatan",
                                      contentBody: Strings.alreadyOut,
                                      buttonText: "Ok",
                                      tapButtonOk: () {
                                        Navigator.pushNamed(
                                          context,
                                          Routes.absentCamera,
                                          arguments: AbsentCameraArguments(
                                            isIn: false,
                                            branchModel: widget
                                                .nearestBranch[selectedOutlet],
                                            profile: profileUser,
                                            nik: nikController.text,
                                            shiftNameSelected:
                                                profileUser.shiftSelectedName,
                                            shiftStartTime:
                                                profileUser.shiftStart,
                                            shiftEndTime: profileUser.shiftEnd,
                                          ),
                                        );
                                      },
                                      isActiveCancelButton: true,
                                      tapButtonCancel: () {
                                        Navigator.pop(context);
                                      },
                                    );
                                    return;
                                  }
                                  Navigator.pushNamed(
                                    context,
                                    Routes.absentCamera,
                                    arguments: AbsentCameraArguments(
                                      isIn: false,
                                      branchModel:
                                          widget.nearestBranch[selectedOutlet],
                                      profile: profileUser,
                                      nik: nikController.text,
                                      shiftNameSelected:
                                          profileUser.shiftSelectedName,
                                      shiftStartTime: profileUser.shiftStart,
                                      shiftEndTime: profileUser.shiftEnd,
                                    ),
                                  );
                                }
                              });
                            }
                          },
                        ),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
        )
      ],
    );
  }
}

class SelectOutlet extends StatefulWidget {
  const SelectOutlet({
    super.key,
    required this.nearestBranch,
    this.onSelected,
  });
  final List<BranchModel> nearestBranch;
  final void Function(int)? onSelected;

  @override
  State<SelectOutlet> createState() => _SelectOutletState();
}

class _SelectOutletState extends State<SelectOutlet> {
  int selectedBranchFromList = 0;
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(
        top: AppMargin.m16,
        left: AppMargin.m20,
        right: AppMargin.m20,
      ),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          width: 0.2,
          color: Colors.grey,
        ),
        color: ColorManager.backgroundColor,
        // boxShadow: [
        //   BoxShadow(
        //     color: Colors.grey.withOpacity(0.3),
        //     blurRadius: 2,
        //     offset: const Offset(5, 5),
        //   ),
        // ],
      ),
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.all(
          AppPadding.p15,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "Pilih Outlet",
              style: getSemiBoldStyle(
                color: Colors.black,
                fontSize: 16,
              ),
            ),
            const SizedBox(
              height: 10,
            ),
            // DropdownButtonFormField2(
            //   decoration: InputDecoration(
            //     // hintText: "NIK",
            //     //Add isDense true and zero Padding.
            //     //Add Horizontal padding using buttonPadding and Vertical padding by increasing buttonHeight instead of add Padding here so that The whole TextField Button become clickable, and also the dropdown menu open under The whole TextField Button.
            //     isDense: true,
            //     contentPadding: const EdgeInsets.symmetric(
            //       // horizontal: 18,
            //       vertical: 15,
            //     ),
            //     enabledBorder: OutlineInputBorder(
            //       borderSide: BorderSide(width: 0.4, color: ColorManager.grey),
            //       borderRadius: BorderRadius.circular(5),
            //     ),
            //     focusedBorder: OutlineInputBorder(
            //       borderSide: BorderSide(width: 0.4, color: ColorManager.grey),
            //       borderRadius: BorderRadius.circular(5),
            //     ),
            //     disabledBorder: OutlineInputBorder(
            //       borderSide: BorderSide(width: 0.4, color: ColorManager.grey),
            //       borderRadius: BorderRadius.circular(5),
            //     ),
            //     //Add more decoration as you want here
            //     //Add label If you want but add hint outside the decoration to be aligned in the button perfectly.
            //   ),
            //   isExpanded: true,
            //   // hint: Text(
            //   //   "${widget.nearestBranch[0].name} (${widget.nearestBranch[0].code})",
            //   //   style: const TextStyle(fontSize: 14),
            //   // ),
            //   hint: Row(
            //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
            //     crossAxisAlignment: CrossAxisAlignment.center,
            //     children: [
            //       Expanded(
            //         child: Text(
            //           widget.nearestBranch[0].code,
            //           style: getRegularStyle(
            //             color: Colors.black,
            //             fontSize: 18,
            //             fontFamily: FontConstants.poppins,
            //           ),
            //           maxLines: 1,
            //           overflow: TextOverflow.ellipsis,
            //         ),
            //       ),
            //       const SizedBox(
            //         width: 10,
            //       ),
            //       Text(
            //         "${widget.nearestBranch[0].distance} Km",
            //         style: getRegularStyle(
            //           color: Colors.black,
            //           fontSize: 12,
            //           fontFamily: FontConstants.poppins,
            //         ),
            //       )
            //     ],
            //   ),
            //   iconStyleData: const IconStyleData(
            //     icon: Icon(
            //       Icons.arrow_drop_down,
            //       color: Colors.black45,
            //     ),
            //   ),
            //   items: widget.nearestBranch
            //       .map((branch) => DropdownMenuItem<String>(
            //             value: branch.id,
            //             child: Row(
            //               mainAxisAlignment: MainAxisAlignment.spaceBetween,
            //               crossAxisAlignment: CrossAxisAlignment.center,
            //               children: [
            //                 Expanded(
            //                   child: Text(
            //                     branch.code,
            //                     style: getRegularStyle(
            //                       color: Colors.black,
            //                       fontSize: 18,
            //                       fontFamily: FontConstants.poppins,
            //                     ),
            //                     maxLines: 2,
            //                     overflow: TextOverflow.ellipsis,
            //                   ),
            //                 ),
            //                 const SizedBox(
            //                   width: 10,
            //                 ),
            //                 Text(
            //                   "${branch.distance} Km",
            //                   style: getRegularStyle(
            //                     color: Colors.black,
            //                     fontSize: 12,
            //                     fontFamily: FontConstants.poppins,
            //                   ),
            //                 )
            //               ],
            //             ),
            //           ))
            //       .toList(),
            //   onChanged: (value) {
            //     int selectedBranch = widget.nearestBranch
            //         .indexWhere((element) => element.id == value);
            //     setState(() {
            //       widget.onSelected!(selectedBranch);
            //     });
            //   },
            // )
            GestureDetector(
              onTap: () {
                showModalBottomSheet(
                    backgroundColor: ColorManager.backgroundColor,
                    isScrollControlled: true,
                    context: context,
                    builder: (c) {
                      return WidgetSelectOutlet(
                        nearestBranch: widget.nearestBranch,
                        selectedOutlet: selectedBranchFromList,
                        onSelected: ((int val) {
                          setState(() {
                            selectedBranchFromList = val;
                            widget.onSelected!(val);
                          });
                        }),
                      );
                    });
              },
              child: Container(
                margin: const EdgeInsets.only(
                  top: 10,
                ),
                width: double.infinity,
                decoration: BoxDecoration(
                  border: Border.all(width: 0.2, color: Colors.grey),
                  borderRadius: BorderRadius.circular(5),
                  color: ColorManager.backgroundColor,
                ),
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 10,
                    vertical: 15,
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Expanded(
                        child: Text(
                          widget.nearestBranch[selectedBranchFromList].name,
                          style: getRegularStyle(
                            color: ColorManager.grey,
                            fontSize: 16,
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      Image(
                        image: AssetImage(
                          Assets.arrowUpDown,
                        ),
                        width: 7,
                        height: 13,
                      )
                      // Icon(
                      //   Icons.arrow_drop_down_sharp,
                      //   color: ColorManager.grey,
                      //   size: 30,
                      // ),
                      // Text(
                      //   "Ubah",
                      //   style: getRegularStyle(
                      //     color: ColorManager.link,
                      //   ),
                      // )
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class WidgetSelectOutlet extends StatefulWidget {
  const WidgetSelectOutlet({
    Key? key,
    this.onSelected,
    required this.nearestBranch,
    required this.selectedOutlet,
  }) : super(key: key);

  final void Function(int val)? onSelected;
  final List<BranchModel> nearestBranch;
  final int selectedOutlet;

  @override
  State<WidgetSelectOutlet> createState() => _WidgetSelectOutletState();
}

class _WidgetSelectOutletState extends State<WidgetSelectOutlet> {
  int selectedOutlet = 0;

  @override
  void initState() {
    selectedOutlet = widget.selectedOutlet;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: EdgeInsets.symmetric(horizontal: AppPadding.p20),
          margin: EdgeInsets.only(top: AppMargin.m20),
          child: Text(
            "Pilih Outlet",
            style: getMediumStyle(
                color: Colors.black,
                fontSize: 20,
                fontFamily: FontConstants.poppins),
          ),
        ),
        Container(
          padding: EdgeInsets.symmetric(horizontal: AppPadding.p20),
          margin: EdgeInsets.only(top: AppMargin.m18),
          child: Center(
            child: Text(
              "Outlet dalam radius ${ConstantString.outletDistance} Km",
              style: getMediumStyle(
                  color: Colors.black,
                  fontSize: 16,
                  fontFamily: FontConstants.poppins),
            ),
          ),
        ),
        Container(
          height: 300,
          width: double.infinity,
          margin: EdgeInsets.only(
            top: AppMargin.m18,
            left: AppMargin.m20,
            right: AppMargin.m20,
          ),
          decoration: BoxDecoration(
            color: ColorManager.backgroundColor,
            borderRadius: BorderRadius.circular(8),
            border: Border.all(width: 0.3, color: ColorManager.grey),
            // boxShadow: [
            //   BoxShadow(
            //     color: Colors.grey.withOpacity(0.3),
            //     blurRadius: 2,
            //     offset: const Offset(5, 5),
            //   ),
            // ],
          ),
          child: ListView.builder(
            padding: EdgeInsets.zero,
            itemCount: widget.nearestBranch.length,
            itemBuilder: ((context, index) {
              return GestureDetector(
                onTap: () {
                  setState(() {
                    selectedOutlet = index;
                  });
                },
                child: Container(
                  margin:
                      const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
                  padding: EdgeInsets.symmetric(
                    horizontal: AppPadding.p10,
                    vertical: AppPadding.p14,
                  ),
                  decoration: BoxDecoration(
                    border: (index + 1 != widget.nearestBranch.length)
                        ? Border(
                            bottom: BorderSide(
                              width: 0.5,
                              color: ColorManager.grey.withOpacity(0.8),
                            ),
                          )
                        : null,
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                        child: Text(
                          widget.nearestBranch[index].name,
                          style: getRegularStyle(
                            color: (selectedOutlet == index)
                                ? ColorManager.link
                                : Colors.black,
                            fontSize: 20,
                            fontFamily: FontConstants.poppins,
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      const SizedBox(
                        width: 10,
                      ),
                      Text(
                        "${widget.nearestBranch[index].distance} Km",
                        style: getRegularStyle(
                          color: (selectedOutlet == index)
                              ? ColorManager.link
                              : Colors.black,
                          fontSize: 12,
                          fontFamily: FontConstants.poppins,
                        ),
                      )
                    ],
                  ),
                ),
              );
            }),
          ),
        ),
        GestureDetector(
          onTap: () {
            widget.onSelected!(selectedOutlet);
            Navigator.pop(context);
          },
          child: Container(
            padding: EdgeInsets.symmetric(
              horizontal: AppPadding.p20,
            ),
            margin: EdgeInsets.symmetric(vertical: AppMargin.m16),
            child: const CustomButton(
              text: "Pilih Outlet",
            ),
          ),
        )
      ],
    );
  }
}

class TimerWidget extends StatefulWidget {
  const TimerWidget({
    Key? key,
  }) : super(key: key);

  @override
  State<TimerWidget> createState() => _TimerWidgetState();
}

class _TimerWidgetState extends State<TimerWidget> {
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    Timer.periodic(const Duration(seconds: 1), (timer) {
      _timer = timer;
      setState(() {});
    });
  }

  @override
  void dispose() {
    super.dispose();

    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(
          DateFormatCustom.getLocalTime(),
          style: getSemiBoldStyle(
            color: Colors.white,
            fontSize: 48,
          ),
        ),
        Text(
          DateFormatCustom.getDateLocal(),
          style: getSemiBoldStyle(
            color: Colors.white,
            fontSize: 14,
          ),
        ),
      ],
    );
  }
}

class WidgetSelectShift extends StatefulWidget {
  const WidgetSelectShift({
    Key? key,
    required this.shiftList,
    required this.branchModel,
    required this.nik,
  }) : super(key: key);

  final List<ShiftModel> shiftList;
  final BranchModel branchModel;
  final String nik;

  @override
  State<WidgetSelectShift> createState() => _WidgetSelectShiftState();
}

class _WidgetSelectShiftState extends State<WidgetSelectShift> {
  int? selectedShift;

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: EdgeInsets.symmetric(horizontal: AppPadding.p20),
          margin: EdgeInsets.only(top: AppMargin.m20),
          child: Text(
            "Pilih Shift",
            style: getMediumStyle(
                color: Colors.black,
                fontSize: 20,
                fontFamily: FontConstants.poppins),
          ),
        ),
        Container(
          height: 300,
          width: double.infinity,
          margin: EdgeInsets.only(
            top: AppMargin.m20,
            left: AppMargin.m20,
            right: AppMargin.m20,
          ),
          decoration: BoxDecoration(
            color: ColorManager.backgroundColor,
            borderRadius: BorderRadius.circular(8),
            border: Border.all(width: 0.3, color: ColorManager.grey),
            // boxShadow: [
            //   BoxShadow(
            //     color: Colors.grey.withOpacity(0.3),
            //     blurRadius: 2,
            //     offset: const Offset(5, 5),
            //   ),
            // ],
          ),
          child: ListView.builder(
            padding: EdgeInsets.zero,
            itemCount: widget.shiftList.length,
            itemBuilder: ((context, index) {
              return GestureDetector(
                onTap: () {
                  setState(() {
                    selectedShift = index;
                  });
                },
                child: Container(
                  margin: const EdgeInsets.symmetric(
                    horizontal: 6,
                    vertical: 3,
                  ),
                  padding: EdgeInsets.symmetric(
                    horizontal: AppPadding.p10,
                    vertical: AppPadding.p14,
                  ),
                  decoration: BoxDecoration(
                    border: (index + 1 != widget.shiftList.length)
                        ? Border(
                            bottom: BorderSide(
                              width: 0.5,
                              color: ColorManager.grey.withOpacity(0.8),
                            ),
                          )
                        : null,
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                        child: Text(
                          widget.shiftList[index].name,
                          style: getRegularStyle(
                            color: (selectedShift == index)
                                ? ColorManager.link
                                : Colors.black,
                            fontSize: FontSize.s16,
                            fontFamily: FontConstants.poppins,
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      const SizedBox(
                        width: 10,
                      ),
                      Text(
                        "${DateFormatCustom.getTimeHourMinuteOnly(widget.shiftList[index].startTime)} - ${DateFormatCustom.getTimeHourMinuteOnly(widget.shiftList[index].endTime)}",
                        style: getRegularStyle(
                          color: (selectedShift == index)
                              ? ColorManager.link
                              : Colors.black,
                          fontSize: FontSize.s20,
                          fontFamily: FontConstants.openSans,
                        ),
                      )
                    ],
                  ),
                ),
              );
            }),
          ),
        ),
        Container(
          padding: EdgeInsets.symmetric(
            horizontal: AppPadding.p20,
          ),
          margin: EdgeInsets.symmetric(vertical: AppMargin.m16),
          child: GestureDetector(
            onTap: () async {
              if (selectedShift != null) {
                await EasyLoading.show(
                  status: Strings.pleaseWait,
                  maskType: EasyLoadingMaskType.none,
                );
                Api.getUserProfile(
                  widget.branchModel.id,
                  widget.nik,
                ).then((apiResponse) {
                  EasyLoading.dismiss();
                  if (apiResponse.error) {
                    modalDialogGlobal(
                        context: context,
                        size: MediaQuery.of(context).size,
                        title: "Gagal",
                        contentBody: apiResponse.msg,
                        buttonText: "Ok",
                        tapButtonOk: () {
                          Navigator.pop(context);
                          Navigator.pop(context);
                        });
                  } else {
                    ProfileModel profileUser = apiResponse.data as ProfileModel;
                    if (profileUser.attendanceIn) {
                      modalDialogGlobal(
                        context: context,
                        size: MediaQuery.of(context).size,
                        title: "Peringatan",
                        contentBody: Strings.alreadyIn,
                        buttonText: "Ok",
                        tapButtonOk: () {
                          Navigator.popAndPushNamed(
                            context,
                            Routes.absentCamera,
                            arguments: AbsentCameraArguments(
                              isIn: true,
                              branchModel: widget.branchModel,
                              shiftModel: widget.shiftList[selectedShift!],
                              profile: profileUser,
                              nik: widget.nik,
                              shiftNameSelected:
                                  widget.shiftList[selectedShift!].name,
                              shiftStartTime:
                                  widget.shiftList[selectedShift!].startTime,
                              shiftEndTime:
                                  widget.shiftList[selectedShift!].endTime,
                            ),
                          );
                        },
                        tapButtonCancel: () {
                          Navigator.pop(context);
                          Navigator.pop(context);
                        },
                        isActiveCancelButton: true,
                      );
                      return;
                    }
                    Navigator.popAndPushNamed(
                      context,
                      Routes.absentCamera,
                      arguments: AbsentCameraArguments(
                        isIn: true,
                        branchModel: widget.branchModel,
                        shiftModel: widget.shiftList[selectedShift!],
                        profile: profileUser,
                        nik: widget.nik,
                        shiftNameSelected:
                            widget.shiftList[selectedShift!].name,
                        shiftStartTime:
                            widget.shiftList[selectedShift!].startTime,
                        shiftEndTime: widget.shiftList[selectedShift!].endTime,
                      ),
                    );
                  }
                });
              } else {
                EasyLoading.showToast("Silakan pilih shift");
              }
            },
            child: CustomButton(
              text: "Pilih",
              colorButton: (selectedShift == null) ? Colors.grey : null,
            ),
          ),
        )
      ],
    );
  }
}
