// ignore_for_file: sized_box_for_whitespace

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:excelso_attendance/api/api.dart';
import 'package:excelso_attendance/helper/arguments/error_args.dart';
import 'package:excelso_attendance/helper/arguments/route_args.dart';
import 'package:excelso_attendance/helper/modal_dialog.dart';
import 'package:excelso_attendance/helper/widget_responsive.dart';
import 'package:excelso_attendance/main.dart';
import 'package:excelso_attendance/models/absent.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/constanta_string.dart';
import 'package:excelso_attendance/resource/routes.dart';
import 'package:excelso_attendance/resource/strings.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'dart:typed_data';

import 'package:camera/camera.dart';
import 'package:excelso_attendance/helper/component/button.dart';
import 'package:excelso_attendance/resource/assets.dart';
import 'package:excelso_attendance/resource/colors.dart';
import 'package:excelso_attendance/resource/font.dart';
import 'package:excelso_attendance/resource/size.dart';
import 'package:excelso_attendance/resource/style.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:quiver/async.dart';

class AbsentCameraView extends StatefulWidget {
  const AbsentCameraView({
    super.key,
    required this.isIn,
    required this.branchModel,
    required this.nik,
    required this.profile,
    this.shiftModel,
    required this.shiftNameSelected,
    required this.shiftStartTime,
    required this.shiftEndTime,
  });

  final bool isIn;
  final BranchModel branchModel;
  final ShiftModel? shiftModel;
  final ProfileModel profile;
  final String nik;
  final String shiftNameSelected;
  final String shiftStartTime;
  final String shiftEndTime;

  @override
  State<AbsentCameraView> createState() => _AbsentCameraViewState();
}

class _AbsentCameraViewState extends State<AbsentCameraView> {
  CameraDescription? _cameraDescription;
  CameraController? _controller;
  Future<void>? _initializeControllerFuture;
  List<CameraDescription>? cameras;
  FlashMode flashMode = FlashMode.off;

  Uint8List? imagePath;
  String? imagePathPhone;
  bool pictureIsTaken = false;
  bool isPhone = false;

  String? imageBase64;

  // bool isPermissionAccept = true;
  // String? errorCamera;

  bool isCameraLoading = true;

  @override
  void initState() {
    super.initState();
    if (kIsWeb) {
      isPhone = false;
    } else {
      isPhone = true;
    }
    initStateFunc();
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  void initStateFunc() {
    getCameraDescrption().then((value) {
      cameras = value;
      if (debug) {
        // ignore: avoid_print
        print("JUMLAH CAMERA TEDETEKSI: ${cameras!.length}");
      }
      for (int i = 0; i < cameras!.length; i++) {
        // detect only fornt camera
        if (cameras![i].lensDirection == CameraLensDirection.front) {
          _cameraDescription = cameras![i];
        }
      }
      // if (cameras!.length > 1) {
      //   _cameraDescription = cameras![0];
      // } else {
      //   if (cameras!.isNotEmpty) {
      //     _cameraDescription = cameras![0];
      //   } else {
      //     _cameraDescription = null;
      //   }
      // }
      // _cameraDescription = cameras![1];

      if (_cameraDescription != null) {
        _controller = CameraController(
          // Get a specific camera from the list of available cameras.
          _cameraDescription!,
          // Define the resolution to use.
          ResolutionPreset.medium,
          imageFormatGroup: ImageFormatGroup.jpeg,
          enableAudio: false,
        );
        initCamera(_controller!);
      } else {
        isCameraLoading = false;
        Navigator.pushNamedAndRemoveUntil(
          context,
          Routes.errorWidget,
          (route) => false,
          arguments: ErrorWidgetArguments(
            errorMessage:
                Strings.cameraFrontNotFound(cameras!.length.toString()),
          ),
        );
      }
    }).catchError((e) {
      if (e is CameraException) {
        switch (e.code) {
          case 'CameraAccessDenied':
            // setState(() {
            //   isPermissionAccept = false;
            // });
            Navigator.pushNamedAndRemoveUntil(
              context,
              Routes.errorWidget,
              (route) => false,
              arguments: ErrorWidgetArguments(
                errorMessage: Strings.cameraNotActive,
              ),
            );
            break;
          default:
            // setState(() {
            //   errorCamera = "$e";
            // });
            // Navigator.pushNamedAndRemoveUntil(
            //   context,
            //   Routes.errorWidget,
            //   (route) => false,
            //   arguments: ErrorWidgetArguments(
            //     errorMessage: "ERROR: $e",
            //   ),
            // );
            modalDialogGlobal(
              context: context,
              size: MediaQuery.of(context).size,
              title: "Error",
              contentBody: "$e",
              buttonText: "OK",
              tapButtonOk: () {
                Navigator.pop(context);
              },
            );
            if (debug) {
              // ignore: avoid_print
              print("CAMERA PERMISSION PROB ERROR: $e");
            }
        }
      } else {
        modalDialogGlobal(
          context: context,
          size: MediaQuery.of(context).size,
          title: "Error",
          contentBody: "$e",
          buttonText: "OK",
          tapButtonOk: () {
            Navigator.pop(context);
          },
        );
      }
    });
  }

  void recallCamera() {
    _controller?.dispose().then((_) {
      setState(() {});
      setState(() {
        pictureIsTaken = false;
        _controller = CameraController(
          // Get a specific camera from the list of available cameras.
          _cameraDescription!,
          // Define the resolution to use.
          ResolutionPreset.medium,
          imageFormatGroup: ImageFormatGroup.jpeg,
          enableAudio: false,
        );
        initCamera(_controller!);
      });
    });
  }

  Future<void> initCamera(CameraController c) async {
    c.initialize().then((_) {
      if (!mounted) {
        Navigator.pushNamedAndRemoveUntil(
          context,
          Routes.errorWidget,
          (route) => false,
          arguments: ErrorWidgetArguments(
            errorMessage: Strings.cameraNotMounted,
          ),
        );
        return;
      }
      setState(() {
        isCameraLoading = false;
      });
    }).catchError((e) {
      setState(() {
        isCameraLoading = false;
      });
      if (e is CameraException) {
        switch (e.code) {
          case 'CameraAccessDenied':
            // setState(() {
            //   isPermissionAccept = false;
            // });
            Navigator.pushNamedAndRemoveUntil(
              context,
              Routes.errorWidget,
              (route) => false,
              arguments: ErrorWidgetArguments(
                errorMessage: Strings.cameraNotActive,
              ),
            );
            break;
          default:
            // setState(() {
            //   errorCamera = "$e";
            // });
            // Navigator.pushNamedAndRemoveUntil(
            //   context,
            //   Routes.errorWidget,
            //   (route) => false,
            //   arguments: ErrorWidgetArguments(
            //     errorMessage: "ERROR: $e",
            //   ),
            // );

            modalDialogGlobal(
              context: context,
              size: MediaQuery.of(context).size,
              title: "Error",
              contentBody: "$e",
              buttonText: "OK",
              tapButtonOk: () {
                Navigator.pop(context);
              },
            );
            if (debug) {
              // ignore: avoid_print
              print("CAMERA PERMISSION PROB ERROR: $e");
            }
        }
      }
    });
  }

  Future<List<CameraDescription>> getCameraDescrption() async {
    return await availableCameras();
  }

  // untuk mengetahui lama proses taking foto sampai response sukses
  final int _start = 10000;
  // ignore: unused_field
  int _longTime = 0;
  CountdownTimer? countDownTimer;

  void startTimer() {
    // print("START TIMER");
    countDownTimer = CountdownTimer(
      Duration(milliseconds: _start),
      const Duration(milliseconds: 1),
    );

    var sub = countDownTimer!.listen(null);
    sub.onData((duration) {
      setState(() {
        _longTime = duration.elapsed.inMilliseconds;
      });
    });
  }

  void stopTimer() async {
    // const filename = 'processAttendace.txt';
//     String typeAbsen;
//     if (widget.isIn) {
//       typeAbsen = "Masuk";
//     } else {
//       typeAbsen = 'Keluar';
//     }
//     String content = '''User Name: ${widget.profile.name}
// Lama proses absen $typeAbsen : $_longTime ms

// ''';

    // print("TIMER STOP");
    // print("LAMA PROSES $_longTime miliseconds");
    countDownTimer!.cancel();
    // await File(filename).writeAsString(content, mode: FileMode.append);
    // sendTotelegram(content);
  }

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

  Column bodyWidget(Size size) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        isCameraLoading
            ? const Center(child: CircularProgressIndicator())
            : Stack(
                children: [
                  Container(
                    width: size.width,
                    height: size.height,
                    padding: EdgeInsets.only(
                        top: AppPadding.safeAreaTop(context) + 40),
                    child: (pictureIsTaken)
                        ? (isPhone)
                            ? Image.file(
                                File(imagePathPhone!),
                                fit: BoxFit.fill,
                              )
                            : Image.memory(
                                imagePath!,
                                // fit: BoxFit.fill,
                              )
                        : CameraPreview(
                            _controller!,
                          ),
                  ),
                  Container(
                    width: size.width,
                    height: size.height,
                    padding: EdgeInsets.only(
                        top: AppPadding.safeAreaTop(context) + 40),
                    child: Image(
                      fit: BoxFit.fill,
                      image: AssetImage(Assets.frameOverlay),
                    ),
                  ),
                  Container(
                    width: size.width,
                    height: size.height,
                    child: Column(
                      children: [
                        Container(
                          height: AppPadding.safeAreaTop(context) + 60,
                          width: double.infinity,
                          decoration: BoxDecoration(
                            borderRadius: const BorderRadius.only(
                              bottomRight: Radius.circular(20),
                              bottomLeft: Radius.circular(20),
                            ),
                            color: ColorManager.primary,
                          ),
                          child: Container(
                            padding: EdgeInsets.symmetric(
                                horizontal: AppPadding.p20),
                            margin: EdgeInsets.only(
                              top: AppPadding.safeAreaTop(context),
                            ),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                GestureDetector(
                                  onTap: () {
                                    Navigator.pop(context);
                                  },
                                  child: const Icon(
                                    Icons.arrow_back,
                                    color: Colors.white,
                                    size: 24,
                                  ),
                                ),
                                Container(
                                  margin: EdgeInsets.only(
                                    left: AppMargin.m16,
                                  ),
                                  child: Text(
                                    "Verifikasi Wajah",
                                    style: getBoldStyle(
                                      color: Colors.white,
                                      fontSize: 17,
                                    ),
                                  ),
                                )
                              ],
                            ),
                          ),
                        ),
                        const SizedBox(
                          height: 15,
                        ),
                        // Expanded(
                        //   child: WidgetAbsentAndTime(
                        //     isIn: widget.isIn,
                        //     outletName: widget.branchModel.name,
                        //     profile: widget.profile,
                        //     nik: widget.nik,
                        //   ),
                        // ),
                        InfoUserAttendance(
                          widget: widget,
                          shift: widget.shiftNameSelected,
                          shiftStart: widget.shiftStartTime,
                          shiftEnd: widget.shiftEndTime,
                        ),
                        const Spacer(),
                        (pictureIsTaken)
                            ? Container(
                                margin: EdgeInsets.symmetric(
                                  horizontal: AppMargin.m20,
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    CustomButton(
                                      text: "Submit",
                                      onTap: () async {
                                        startTimer();
                                        await EasyLoading.show(
                                          status: Strings.pleaseWait,
                                          maskType: EasyLoadingMaskType.none,
                                        );
                                        if (widget.isIn) {
                                          Api.shiftIn(
                                            widget.branchModel.id,
                                            widget.nik,
                                            widget.shiftModel!.id,
                                            imageBase64!,
                                          ).then((apiResponse) {
                                            stopTimer();
                                            EasyLoading.dismiss();
                                            if (apiResponse.error) {
                                              modalDialogGlobal(
                                                context: context,
                                                size:
                                                    MediaQuery.of(context).size,
                                                title: "Gagal",
                                                contentBody: apiResponse.msg,
                                                buttonText: "OK",
                                                tapButtonOk: () {
                                                  Navigator.pop(context);
                                                  recallCamera();
                                                },
                                              );
                                              return;
                                            }
                                            AbsentSuccessModel absentSuccess =
                                                apiResponse.data
                                                    as AbsentSuccessModel;
                                            Navigator.pushNamedAndRemoveUntil(
                                              context,
                                              Routes.absentSuccess,
                                              (route) => false,
                                              arguments: AbsentSuccessArguments(
                                                  absentSuccess: absentSuccess,
                                                  profil: widget.profile,
                                                  nik: widget.nik,
                                                  isIn: true,
                                                  shiftName:
                                                      widget.shiftNameSelected,
                                                  shiftEnd: widget.shiftEndTime,
                                                  shiftStart:
                                                      widget.shiftStartTime),
                                            );
                                          });
                                        } else {
                                          Api.shiftOut(
                                            widget.branchModel.id,
                                            widget.nik,
                                            imageBase64!,
                                          ).then((apiResponse) {
                                            stopTimer();
                                            EasyLoading.dismiss();
                                            if (apiResponse.error) {
                                              modalDialogGlobal(
                                                context: context,
                                                size:
                                                    MediaQuery.of(context).size,
                                                title: "Gagal",
                                                contentBody: apiResponse.msg,
                                                buttonText: "OK",
                                                tapButtonOk: () {
                                                  Navigator.pop(context);
                                                  recallCamera();
                                                },
                                              );
                                              return;
                                            }
                                            AbsentSuccessModel absentSuccess =
                                                apiResponse.data
                                                    as AbsentSuccessModel;
                                            Navigator.pushNamedAndRemoveUntil(
                                              context,
                                              Routes.absentSuccess,
                                              (route) => false,
                                              arguments: AbsentSuccessArguments(
                                                  absentSuccess: absentSuccess,
                                                  profil: widget.profile,
                                                  nik: widget.nik,
                                                  isIn: false,
                                                  shiftName:
                                                      widget.shiftNameSelected,
                                                  shiftEnd: widget.shiftEndTime,
                                                  shiftStart:
                                                      widget.shiftStartTime),
                                            );
                                          });
                                        }
                                      },
                                    ),
                                    SizedBox(
                                      height: AppMargin.m8,
                                    ),
                                    CustomButton(
                                      text: "Foto Ulang",
                                      colorButton: Colors.red,
                                      onTap: () {
                                        recallCamera();
                                      },
                                    )
                                    // Container(
                                    //   width: 100,
                                    //   child: CustomButton(
                                    //     text: "Submit",
                                    //     onTap: () async {
                                    //       // startTimer();
                                    //       await EasyLoading.show(
                                    //         status: Strings.pleaseWait,
                                    //         maskType: EasyLoadingMaskType.none,
                                    //       );
                                    //       if (widget.isIn) {
                                    //         Api.shiftIn(
                                    //           widget.branchModel.id,
                                    //           widget.nik,
                                    //           widget.shiftModel!.id,
                                    //           imageBase64!,
                                    //         ).then((apiResponse) {
                                    //           // stopTimer();
                                    //           EasyLoading.dismiss();
                                    //           if (apiResponse.error) {
                                    //             EasyLoading.showToast(
                                    //                 apiResponse.msg);
                                    //             return;
                                    //           }
                                    //           AbsentSuccessModel absentSuccess =
                                    //               apiResponse.data
                                    //                   as AbsentSuccessModel;
                                    //           Navigator.pushNamedAndRemoveUntil(
                                    //             context,
                                    //             Routes.absentSuccess,
                                    //             (route) => false,
                                    //             arguments: AbsentSuccessArguments(
                                    //               absentSuccess: absentSuccess,
                                    //               isIn: true,
                                    //             ),
                                    //           );
                                    //         });
                                    //       } else {
                                    //         Api.shiftOut(
                                    //           widget.branchModel.id,
                                    //           widget.nik,
                                    //           imageBase64!,
                                    //         ).then((apiResponse) {
                                    //           // stopTimer();
                                    //           EasyLoading.dismiss();
                                    //           if (apiResponse.error) {
                                    //             EasyLoading.showToast(
                                    //               apiResponse.msg,
                                    //             );
                                    //             return;
                                    //           }
                                    //           AbsentSuccessModel absentSuccess =
                                    //               apiResponse.data
                                    //                   as AbsentSuccessModel;
                                    //           Navigator.pushNamedAndRemoveUntil(
                                    //             context,
                                    //             Routes.absentSuccess,
                                    //             (route) => false,
                                    //             arguments: AbsentSuccessArguments(
                                    //               absentSuccess: absentSuccess,
                                    //               isIn: false,
                                    //             ),
                                    //           );
                                    //         });
                                    //       }
                                    //     },
                                    //   ),
                                    // ),
                                    // Container(
                                    //   width: 100,
                                    //   margin: const EdgeInsets.only(
                                    //     top: 10,
                                    //   ),
                                    //   child: GestureDetector(
                                    //     onTap: () async {
                                    //       _controller?.dispose().then((_) {
                                    //         setState(() {});
                                    //         setState(() {
                                    //           pictureIsTaken = false;
                                    //           _controller = CameraController(
                                    //             // Get a specific camera from the list of available cameras.
                                    //             _cameraDescription!,
                                    //             // Define the resolution to use.
                                    //             ResolutionPreset.medium,
                                    //             imageFormatGroup:
                                    //                 ImageFormatGroup.jpeg,
                                    //             enableAudio: false,
                                    //           );
                                    //           initCamera(_controller!);
                                    //         });
                                    //       });
                                    //     },
                                    //     child: CustomButton(
                                    //       text: "Foto Ulang",
                                    //       colorButton: ColorManager.grey,
                                    //     ),
                                    //   ),
                                    // ),
                                  ],
                                ),
                              )
                            : Stack(
                                children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      // GestureDetector(
                                      //   onTap: () {
                                      //     if (flashMode ==
                                      //         FlashMode.always) {
                                      //       flashMode = FlashMode.off;
                                      //     } else {
                                      //       flashMode = FlashMode.always;
                                      //     }
                                      //     setState(() {
                                      //       _controller!
                                      //           .setFlashMode(flashMode);
                                      //     });
                                      //   },
                                      //   child: Icon(
                                      //     Icons.flash_auto,
                                      //     size: 35,
                                      //     color: ColorManager.primary,
                                      //   ),
                                      // ),
                                      const SizedBox(
                                        width: 100,
                                      ),
                                      InkWell(
                                        onTap: () async {
                                          try {
                                            await _initializeControllerFuture;

                                            // ambil imagenya
                                            XFile image = await _controller!
                                                .takePicture();
                                            String? imageResultPhone;
                                            Uint8List? imageResultWeb;
                                            if (isPhone) {
                                              imageResultPhone = image.path;
                                              imageResultWeb =
                                                  await image.readAsBytes();
                                            } else {
                                              imageResultWeb =
                                                  await image.readAsBytes();
                                            }

                                            // kalau gak ke ambil gak ngelakuin aksi apa2
                                            if (!mounted) return;
                                            setState(() {
                                              pictureIsTaken = true;
                                              imagePath = imageResultWeb;
                                              imagePathPhone = imageResultPhone;
                                              imageBase64 =
                                                  base64Encode(imageResultWeb!);
                                            });
                                          } catch (e) {
                                            if (debug) {
                                              // ignore: avoid_print
                                              print(
                                                  "TERJADI KESALAHAAN SAAT AMBIL GAMBER, ERROR: $e");
                                            }
                                          }
                                        },
                                        child: Container(
                                          width: 80,
                                          height: 80,
                                          decoration: BoxDecoration(
                                            borderRadius:
                                                BorderRadius.circular(100),
                                            border: Border.all(
                                              width: 1.5,
                                              color: Colors.black,
                                            ),
                                            color: Colors.red,
                                          ),
                                        ),
                                      ),
                                      const SizedBox(
                                        width: 60,
                                      ),
                                      GestureDetector(
                                        onTap: () async {
                                          if (cameras!.length > 1) {
                                            _controller
                                                ?.dispose()
                                                .then((value) {
                                              setState(() {});
                                              CameraDescription? switchTo;
                                              if (_cameraDescription ==
                                                  cameras![0]) {
                                                _cameraDescription =
                                                    cameras![1];
                                                switchTo = cameras![1];
                                              } else {
                                                _cameraDescription =
                                                    cameras![0];
                                                switchTo = cameras![0];
                                              }
                                              _controller = CameraController(
                                                switchTo,
                                                ResolutionPreset.medium,
                                                imageFormatGroup:
                                                    ImageFormatGroup.jpeg,
                                                enableAudio: false,
                                              );
                                              initCamera(_controller!);
                                            });
                                          } else {
                                            EasyLoading.showToast(
                                                "Kamera lain tidak terdeteksi");
                                          }
                                        },
                                        child: Icon(
                                          Icons.switch_camera_outlined,
                                          size: 35,
                                          color: ColorManager.primary,
                                        ),
                                      )
                                    ],
                                  ),
                                ],
                              ),
                        const SizedBox(
                          height: 30,
                        )
                      ],
                    ),
                  ),
                ],
              )
        // (isPermissionAccept) ?
        // (_initializeControllerFuture != null)
        //     ? FutureBuilder(
        //         future: _initializeControllerFuture,
        //         builder: ((context, snapshot) {
        //           if (snapshot.connectionState == ConnectionState.done) {
        //             return Stack(
        //               children: [
        //                 Container(
        //                   width: size.width,
        //                   height: size.height,
        //                   padding: EdgeInsets.only(
        //                       top: AppPadding.safeAreaTop(context) + 40),
        //                   child: (pictureIsTaken)
        //                       ? (isPhone)
        //                           ? Image.file(
        //                               File(imagePathPhone!),
        //                               fit: BoxFit.fill,
        //                             )
        //                           : Image.memory(
        //                               imagePath!,
        //                               // fit: BoxFit.fill,
        //                             )
        //                       : CameraPreview(
        //                           _controller!,
        //                         ),
        //                 ),
        //                 Container(
        //                   width: size.width,
        //                   height: size.height,
        //                   padding: EdgeInsets.only(
        //                       top: AppPadding.safeAreaTop(context) + 40),
        //                   child: Image(
        //                     fit: BoxFit.fill,
        //                     image: AssetImage(Assets.frameOverlay),
        //                   ),
        //                 ),
        //                 Container(
        //                   width: size.width,
        //                   height: size.height,
        //                   child: Column(
        //                     children: [
        //                       Container(
        //                         height: AppPadding.safeAreaTop(context) + 60,
        //                         width: double.infinity,
        //                         decoration: BoxDecoration(
        //                           borderRadius: const BorderRadius.only(
        //                             bottomRight: Radius.circular(20),
        //                             bottomLeft: Radius.circular(20),
        //                           ),
        //                           color: ColorManager.primary,
        //                         ),
        //                         child: Container(
        //                           padding: EdgeInsets.symmetric(
        //                               horizontal: AppPadding.p20),
        //                           margin: EdgeInsets.only(
        //                             top: AppPadding.safeAreaTop(context),
        //                           ),
        //                           child: Row(
        //                             crossAxisAlignment:
        //                                 CrossAxisAlignment.center,
        //                             children: [
        //                               GestureDetector(
        //                                 onTap: () {
        //                                   Navigator.pop(context);
        //                                 },
        //                                 child: const Icon(
        //                                   Icons.arrow_back,
        //                                   color: Colors.white,
        //                                   size: 24,
        //                                 ),
        //                               ),
        //                               Container(
        //                                 margin: EdgeInsets.only(
        //                                   left: AppMargin.m16,
        //                                 ),
        //                                 child: Text(
        //                                   "Verifikasi Wajah (${cameras!.length})",
        //                                   style: getBoldStyle(
        //                                     color: Colors.white,
        //                                     fontSize: 17,
        //                                   ),
        //                                 ),
        //                               )
        //                             ],
        //                           ),
        //                         ),
        //                       ),
        //                       const SizedBox(
        //                         height: 15,
        //                       ),
        //                       WidgetAbsentAndTime(
        //                         isIn: widget.isIn,
        //                         outletName: widget.branchModel.code,
        //                       ),
        //                       const Spacer(),
        //                       (pictureIsTaken)
        //                           ? Column(
        //                               crossAxisAlignment:
        //                                   CrossAxisAlignment.center,
        //                               children: [
        //                                 Container(
        //                                   width: 100,
        //                                   child: CustomButton(
        //                                     text: "Submit",
        //                                     onTap: () async {
        //                                       // startTimer();
        //                                       await EasyLoading.show(
        //                                         status: Strings.pleaseWait,
        //                                         maskType:
        //                                             EasyLoadingMaskType.none,
        //                                       );
        //                                       if (widget.isIn) {
        //                                         Api.shiftIn(
        //                                           widget.branchModel.id,
        //                                           widget.nik,
        //                                           widget.shiftModel!.id,
        //                                           imageBase64!,
        //                                         ).then((apiResponse) {
        //                                           // stopTimer();
        //                                           EasyLoading.dismiss();
        //                                           if (apiResponse.error) {
        //                                             EasyLoading.showToast(
        //                                                 apiResponse.msg);
        //                                             return;
        //                                           }
        //                                           AbsentSuccessModel
        //                                               absentSuccess =
        //                                               apiResponse.data
        //                                                   as AbsentSuccessModel;
        //                                           Navigator
        //                                               .pushNamedAndRemoveUntil(
        //                                             context,
        //                                             Routes.absentSuccess,
        //                                             (route) => false,
        //                                             arguments:
        //                                                 AbsentSuccessArguments(
        //                                               absentSuccess:
        //                                                   absentSuccess,
        //                                               isIn: true,
        //                                             ),
        //                                           );
        //                                         });
        //                                       } else {
        //                                         Api.shiftOut(
        //                                           widget.branchModel.id,
        //                                           widget.nik,
        //                                           imageBase64!,
        //                                         ).then((apiResponse) {
        //                                           // stopTimer();
        //                                           EasyLoading.dismiss();
        //                                           if (apiResponse.error) {
        //                                             EasyLoading.showToast(
        //                                               apiResponse.msg,
        //                                             );
        //                                             return;
        //                                           }
        //                                           AbsentSuccessModel
        //                                               absentSuccess =
        //                                               apiResponse.data
        //                                                   as AbsentSuccessModel;
        //                                           Navigator
        //                                               .pushNamedAndRemoveUntil(
        //                                             context,
        //                                             Routes.absentSuccess,
        //                                             (route) => false,
        //                                             arguments:
        //                                                 AbsentSuccessArguments(
        //                                               absentSuccess:
        //                                                   absentSuccess,
        //                                               isIn: false,
        //                                             ),
        //                                           );
        //                                         });
        //                                       }
        //                                     },
        //                                   ),
        //                                 ),
        //                                 Container(
        //                                   width: 100,
        //                                   margin: const EdgeInsets.only(
        //                                     top: 10,
        //                                   ),
        //                                   child: GestureDetector(
        //                                     onTap: () {
        //                                       setState(() {
        //                                         pictureIsTaken = false;
        //                                         _controller = CameraController(
        //                                           // Get a specific camera from the list of available cameras.
        //                                           _cameraDescription!,
        //                                           // Define the resolution to use.
        //                                           ResolutionPreset.medium,
        //                                           imageFormatGroup:
        //                                               ImageFormatGroup.jpeg,
        //                                         );
        //                                         _initializeControllerFuture =
        //                                             _controller!.initialize();
        //                                       });
        //                                     },
        //                                     child: CustomButton(
        //                                       text: "Foto Ulang",
        //                                       colorButton: ColorManager.grey,
        //                                     ),
        //                                   ),
        //                                 ),
        //                               ],
        //                             )
        //                           : Stack(
        //                               children: [
        //                                 Row(
        //                                   mainAxisAlignment:
        //                                       MainAxisAlignment.center,
        //                                   children: [
        //                                     // GestureDetector(
        //                                     //   onTap: () {
        //                                     //     if (flashMode ==
        //                                     //         FlashMode.always) {
        //                                     //       flashMode = FlashMode.off;
        //                                     //     } else {
        //                                     //       flashMode = FlashMode.always;
        //                                     //     }
        //                                     //     setState(() {
        //                                     //       _controller!
        //                                     //           .setFlashMode(flashMode);
        //                                     //     });
        //                                     //   },
        //                                     //   child: Icon(
        //                                     //     Icons.flash_auto,
        //                                     //     size: 35,
        //                                     //     color: ColorManager.primary,
        //                                     //   ),
        //                                     // ),
        //                                     const SizedBox(
        //                                       width: 100,
        //                                     ),
        //                                     InkWell(
        //                                       onTap: () async {
        //                                         try {
        //                                           await _initializeControllerFuture;

        //                                           // ambil imagenya
        //                                           XFile image =
        //                                               await _controller!
        //                                                   .takePicture();
        //                                           String? imageResultPhone;
        //                                           Uint8List? imageResultWeb;
        //                                           if (isPhone) {
        //                                             imageResultPhone =
        //                                                 image.path;
        //                                             imageResultWeb = await image
        //                                                 .readAsBytes();
        //                                           } else {
        //                                             imageResultWeb = await image
        //                                                 .readAsBytes();
        //                                           }

        //                                           // kalau gak ke ambil gak ngelakuin aksi apa2
        //                                           if (!mounted) return;
        //                                           setState(() {
        //                                             pictureIsTaken = true;
        //                                             imagePath = imageResultWeb;
        //                                             imagePathPhone =
        //                                                 imageResultPhone;
        //                                             imageBase64 = base64Encode(
        //                                                 imageResultWeb!);
        //                                           });
        //                                         } catch (e) {
        //                                           if (debug) {
        //                                             // ignore: avoid_print
        //                                             print(
        //                                                 "TERJADI KESALAHAAN SAAT AMBIL GAMBER, ERROR: $e");
        //                                           }
        //                                         }
        //                                       },
        //                                       child: Container(
        //                                         width: 80,
        //                                         height: 80,
        //                                         decoration: BoxDecoration(
        //                                           borderRadius:
        //                                               BorderRadius.circular(
        //                                                   100),
        //                                           border: Border.all(
        //                                             width: 1.5,
        //                                             color: Colors.black,
        //                                           ),
        //                                           color: Colors.red,
        //                                         ),
        //                                       ),
        //                                     ),
        //                                     const SizedBox(
        //                                       width: 60,
        //                                     ),
        //                                     GestureDetector(
        //                                       onTap: () {
        //                                         if (cameras!.length > 1) {
        //                                           setState(() {
        //                                             if (_cameraDescription ==
        //                                                 cameras![0]) {
        //                                               _cameraDescription =
        //                                                   cameras![1];
        //                                             } else {
        //                                               _cameraDescription =
        //                                                   cameras![0];
        //                                             }

        //                                             _controller =
        //                                                 CameraController(
        //                                               // Get a specific camera from the list of available cameras.
        //                                               _cameraDescription!,
        //                                               // Define the resolution to use.
        //                                               ResolutionPreset.medium,
        //                                               imageFormatGroup:
        //                                                   ImageFormatGroup.jpeg,
        //                                             );
        //                                             _initializeControllerFuture =
        //                                                 _controller!
        //                                                     .initialize();
        //                                           });
        //                                         } else {
        //                                           EasyLoading.showToast(
        //                                               "Kamera lain tidak terdeteksi");
        //                                         }
        //                                       },
        //                                       child: Icon(
        //                                         Icons.switch_camera_outlined,
        //                                         size: 35,
        //                                         color: ColorManager.primary,
        //                                       ),
        //                                     )
        //                                   ],
        //                                 ),
        //                               ],
        //                             ),
        //                       const SizedBox(
        //                         height: 30,
        //                       )
        //                     ],
        //                   ),
        //                 ),
        //               ],
        //             );
        //           } else {
        //             return const Center(child: CircularProgressIndicator());
        //           }
        //         }),
        //       )
        //     : const Center(child: CircularProgressIndicator())
        // : Center(
        //     child: Padding(
        //       padding: EdgeInsets.symmetric(
        //         horizontal: AppPadding.p20,
        //       ),
        //       child: Column(
        //         children: [
        //           Text(
        //             "Silakan aktifkan permission kamera pada pengaturan browser anda",
        //             style: getBoldStyle(
        //               color: Colors.black,
        //               fontSize: 16,
        //             ),
        //             textAlign: TextAlign.center,
        //           ),
        //           (errorCamera != null)
        //               ? Container(
        //                   margin: const EdgeInsets.only(
        //                     top: 10,
        //                   ),
        //                   child: Text(
        //                     "Error; $errorCamera",
        //                     style: getBoldStyle(
        //                       color: Colors.black,
        //                       fontSize: 16,
        //                     ),
        //                   ),
        //                 )
        //               : const SizedBox(),
        //           // const SizedBox(
        //           //   height: 10,
        //           // ),
        //           // CustomButton(
        //           //   text: "Aktifkan kamera",
        //           //   onTap: () async {
        //           //     final perm = await html.window.navigator.permissions!
        //           //         .query({"name": "camera"});
        //           //     if (perm.state == "denied") {
        //           //       print("DENIED");
        //           //       await html.window.navigator
        //           //           .getUserMedia(audio: true, video: true);
        //           //       return;
        //           //     }
        //           //     final stream = await html.window.navigator
        //           //         .getUserMedia(video: true);
        //           //   },
        //           // )
        //         ],
        //       ),
        //     ),
        //   )
      ],
    );
  }
}

class InfoUserAttendance extends StatefulWidget {
  const InfoUserAttendance({
    super.key,
    required this.widget,
    required this.shift,
    required this.shiftStart,
    required this.shiftEnd,
  });

  final AbsentCameraView widget;
  final String shift;
  final String shiftStart;
  final String shiftEnd;

  @override
  State<InfoUserAttendance> createState() => _InfoUserAttendanceState();
}

class _InfoUserAttendanceState extends State<InfoUserAttendance> {
  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 Container(
      margin: EdgeInsets.symmetric(
        horizontal: AppMargin.m20,
      ),
      padding: EdgeInsets.symmetric(
        horizontal: AppPadding.p15,
        vertical: AppPadding.p12,
      ),
      width: double.infinity,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.white,
      ),
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.symmetric(
              vertical: 5,
            ),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  width: 0.8,
                  color: ColorManager.grey.withOpacity(0.2),
                ),
              ),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                (ConstantString.logoUrlCamera == "")
                    ? const Image(
                        width: 111,
                        height: 43,
                        image: AssetImage(
                          "",
                        ),
                      )
                    : Image(
                        width: 111,
                        height: 43,
                        image: NetworkImage(
                          ConstantString.logoUrlCamera,
                        ),
                      ),
                const SizedBox(
                  width: 40,
                ),
                Expanded(
                  child: Text(
                    widget.widget.branchModel.name,
                    style: getSemiBoldStyle(
                      color: Colors.black,
                      fontSize: FontSize.s16,
                    ),
                    textAlign: TextAlign.end,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                )
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.only(
              top: AppPadding.p12,
              bottom: AppPadding.p16,
            ),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  width: 0.8,
                  color: ColorManager.grey.withOpacity(0.2),
                ),
              ),
            ),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      child: Text(
                        widget.widget.profile.name,
                        style: getSemiBoldStyle(
                          color: Colors.black,
                          fontSize: FontSize.s14,
                          fontFamily: FontConstants.k2d,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    const SizedBox(
                      width: 30,
                    ),
                    const Spacer(),
                    Expanded(
                      child: Text(
                        widget.widget.nik,
                        style: getSemiBoldStyle(
                          color: ColorManager.green2,
                          fontSize: FontSize.s14,
                          fontFamily: FontConstants.k2d,
                        ),
                        textAlign: TextAlign.end,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: AppMargin.m8,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      child: Text(
                        widget.shift,
                        style: getSemiBoldStyle(
                          color: Colors.black,
                          fontSize: FontSize.s14,
                          fontFamily: FontConstants.k2d,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    const SizedBox(
                      width: 20,
                    ),
                    Expanded(
                      child: Text(
                        "${widget.shiftStart} - ${widget.shiftEnd}",
                        style: getRegularStyle(
                          color: Colors.black,
                          fontSize: FontSize.s12,
                          fontFamily: FontConstants.k2d,
                        ),
                        textAlign: TextAlign.end,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(
              top: AppMargin.m10,
            ),
            child: Text(
              (widget.widget.isIn) ? "Absen Masuk" : "Absen Keluar",
              style: getMediumStyle(
                color: Colors.black,
                fontSize: FontSize.s16,
                fontFamily: FontConstants.poppins,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

// class WidgetAbsentAndTime extends StatefulWidget {
//   const WidgetAbsentAndTime({
//     Key? key,
//     required this.outletName,
//     required this.isIn,
//     required this.nik,
//     required this.profile,
//   }) : super(key: key);

//   final String outletName;
//   final bool isIn;
//   final String nik;
//   final ProfileModel profile;

//   @override
//   State<WidgetAbsentAndTime> createState() => _WidgetAbsentAndTimeState();
// }

// class _WidgetAbsentAndTimeState extends State<WidgetAbsentAndTime> {
//   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 Container(
//       margin: EdgeInsets.symmetric(
//         horizontal: AppMargin.m20,
//       ),
//       decoration: BoxDecoration(
//         borderRadius: BorderRadius.circular(12),
//         color: Colors.white,
//       ),
//       padding: EdgeInsets.symmetric(
//         horizontal: AppPadding.p20,
//         vertical: AppPadding.p12,
//       ),
//       width: double.infinity,
//       height: 160,
//       child: Column(
//         crossAxisAlignment: CrossAxisAlignment.center,
//         mainAxisAlignment: MainAxisAlignment.spaceBetween,
//         mainAxisSize: MainAxisSize.min,
//         children: [
//           Image(
//             image: AssetImage(
//               Assets.excelsoLogoGreen,
//             ),
//             width: 100,
//             height: 30,
//           ),
//           const SizedBox(
//             height: 10,
//           ),
//           Text(
//             "${widget.outletName} - ${DateFormatCustom.getLocalTime(
//               timeZoneActive: true,
//             )}",
//             style: getSemiBoldStyle(
//               color: Colors.black,
//               fontSize: FontSize.s16,
//             ),
//             maxLines: 2,
//             overflow: TextOverflow.ellipsis,
//             textAlign: TextAlign.center,
//           ),
//           Text(
//             "[${widget.nik}] ${widget.profile.name}",
//             style: getSemiBoldStyle(
//               color: Colors.black,
//               fontSize: FontSize.s14,
//               fontFamily: FontConstants.poppins,
//             ),
//             maxLines: 1,
//             overflow: TextOverflow.ellipsis,
//             textAlign: TextAlign.center,
//           ),
//           // Expanded(
//           //   child: Text(
//           //     widget.nik,
//           //     style: getSemiBoldStyle(
//           //       color: Colors.black,
//           //       fontSize: FontSize.s16,
//           //       fontFamily: FontConstants.poppins,
//           //     ),
//           //     maxLines: 2,
//           //     overflow: TextOverflow.ellipsis,
//           //     textAlign: TextAlign.center,
//           //   ),
//           // ),
//           Text(
//             (widget.isIn) ? "Absen Masuk" : "Absen Keluar",
//             style: getSemiBoldStyle(
//               color: Colors.black,
//               fontSize: FontSize.s14,
//               fontFamily: FontConstants.poppins,
//             ),
//           ),
//         ],
//       ),
//     );
//   }
// }
