// ignore_for_file: sized_box_for_whitespace, use_build_context_synchronously

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:ravintola_attendance/api/api.dart';
import 'package:ravintola_attendance/api/base_api.dart';
import 'package:ravintola_attendance/helper/arguments/error_args.dart';
import 'package:ravintola_attendance/helper/arguments/route_args.dart';
import 'package:ravintola_attendance/helper/modal_dialog.dart';
import 'package:ravintola_attendance/helper/widget_responsive.dart';
import 'package:ravintola_attendance/main.dart';
import 'package:ravintola_attendance/models/absent.dart';
import 'package:ravintola_attendance/models/branch.dart';
import 'package:ravintola_attendance/models/profile.dart';
import 'package:ravintola_attendance/models/shift.dart';
import 'package:ravintola_attendance/resource/routes.dart';
import 'package:ravintola_attendance/resource/strings.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'dart:typed_data';

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

String getAbsentText(bool isIn, int actionType) {
  if (actionType == 1) {
    return isIn ? "Absen Masuk" : "Absen Keluar";
  } else if (actionType == 2) {
    return isIn ? "Break Start" : "Break End";
  }
  return "Unknown";
}

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

  final int actionType; // 1 = Absent, 2 = Break
  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() {
    print("isIn: ${widget.isIn}");
    print("actionType: ${widget.actionType}");

    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];
        }
      }

      // ini kalau gak ada kamera depan, yaudah, ambil camera pertama aja
      if (_cameraDescription == null && cameras!.isNotEmpty) {
        _cameraDescription = cameras![0];
      }

      // 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.actionType == 1) {
                                          if (widget.isIn) {
                                            ApiResponse apiResponse = await Api.shiftIn(
                                              widget.branchModel.id,
                                              widget.nik,
                                              widget.shiftModel!.id,
                                              imageBase64!,
                                            );
                                            // stopTimer();
                                            EasyLoading.dismiss();
                                            if (apiResponse.error) {
                                              // Start modal dialog konfirmasi kalau dia out of range
                                              if (apiResponse.code == "DISTANCE_OUT_OF_RANGE") {
                                                modalDialogGlobal(
                                                  context: context,
                                                  size: MediaQuery.of(context).size,
                                                  title: "Konfirmasi",
                                                  contentBody: apiResponse.msg,
                                                  buttonText: "YA",
                                                  tapButtonOk: () async {
                                                    await EasyLoading.show(
                                                      status: Strings.pleaseWait,
                                                      maskType: EasyLoadingMaskType.none,
                                                    );
                                                    ApiResponse apiResponse = await Api.shiftIn(
                                                      widget.branchModel.id,
                                                      widget.nik,
                                                      widget.shiftModel!.id,
                                                      imageBase64!,
                                                      forceSubmit: 1,
                                                    );
                                                    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);
                                                          recallCamera();
                                                        },
                                                      );
                                                      return;
                                                    } else {
                                                      Navigator.pop(context);
                                                      AbsentSuccessModel absentSuccess =
                                                          apiResponse.data as AbsentSuccessModel;
                                                      Navigator.pushNamedAndRemoveUntil(
                                                        context,
                                                        Routes.absentSuccess,
                                                        (route) => false,
                                                        arguments: AbsentSuccessArguments(
                                                            absentSuccess: absentSuccess,
                                                            profil: widget.profile,
                                                            nik: widget.nik,
                                                            actionType: widget.actionType,
                                                            isIn: true,
                                                            shiftName: widget.shiftNameSelected,
                                                            shiftEnd: widget.shiftEndTime,
                                                            shiftStart: widget.shiftStartTime),
                                                      );

                                                      return;
                                                    }
                                                  },
                                                  isActiveCancelButton: true,
                                                  cancelButtonText: "Tidak",
                                                  tapButtonCancel: () {
                                                    // kalau pilih tidak, recall lagi camera suruh foto ulang
                                                    Navigator.pop(context);
                                                    recallCamera();
                                                  },
                                                );
                                                return;
                                              }
                                              // END modal dialog konfirmasi kalau dia out of range

                                              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,
                                                  actionType: widget.actionType,
                                                  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) {
                                                // Start modal dialog konfirmasi kalau dia out of range
                                                if (apiResponse.code == "DISTANCE_OUT_OF_RANGE") {
                                                  modalDialogGlobal(
                                                    context: context,
                                                    size: MediaQuery.of(context).size,
                                                    title: "Konfirmasi",
                                                    contentBody: apiResponse.msg,
                                                    buttonText: "YA",
                                                    tapButtonOk: () async {
                                                      await EasyLoading.show(
                                                        status: Strings.pleaseWait,
                                                        maskType: EasyLoadingMaskType.none,
                                                      );
                                                      ApiResponse apiResponse = await Api.shiftOut(
                                                        widget.branchModel.id,
                                                        widget.nik,
                                                        imageBase64!,
                                                        forceSubmit: 1,
                                                      );
                                                      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);
                                                            recallCamera();
                                                          },
                                                        );
                                                        return;
                                                      } else {
                                                        Navigator.pop(context);
                                                        AbsentSuccessModel absentSuccess =
                                                            apiResponse.data as AbsentSuccessModel;
                                                        Navigator.pushNamedAndRemoveUntil(
                                                          context,
                                                          Routes.absentSuccess,
                                                          (route) => false,
                                                          arguments: AbsentSuccessArguments(
                                                              absentSuccess: absentSuccess,
                                                              profil: widget.profile,
                                                              nik: widget.nik,
                                                              actionType: widget.actionType,
                                                              isIn: false,
                                                              shiftName: widget.shiftNameSelected,
                                                              shiftEnd: widget.shiftEndTime,
                                                              shiftStart: widget.shiftStartTime),
                                                        );
                                                        return;
                                                      }
                                                    },
                                                    isActiveCancelButton: true,
                                                    cancelButtonText: "Tidak",
                                                    tapButtonCancel: () {
                                                      // kalau pilih tidak, recall lagi camera suruh foto ulang
                                                      Navigator.pop(context);
                                                      recallCamera();
                                                    },
                                                  );
                                                  return;
                                                }
                                                // END modal dialog konfirmasi kalau dia out of range
                                                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,
                                                    actionType: widget.actionType,
                                                    isIn: false,
                                                    shiftName: widget.shiftNameSelected,
                                                    shiftEnd: widget.shiftEndTime,
                                                    shiftStart: widget.shiftStartTime),
                                              );
                                            });
                                          }
                                        }

                                        /** Submit Break, Start and End */
                                        if (widget.actionType == 2) {
                                          Api.submitBreak(
                                            widget.isIn,
                                            widget.branchModel.id,
                                            widget.nik,
                                            imageBase64!,
                                          ).then((apiResponse) {
                                            EasyLoading.dismiss();
                                            if (apiResponse.error) {
                                              // Start modal dialog konfirmasi kalau dia out of range
                                              if (apiResponse.code == "DISTANCE_OUT_OF_RANGE") {
                                                modalDialogGlobal(
                                                  context: context,
                                                  size: MediaQuery.of(context).size,
                                                  title: "Konfirmasi",
                                                  contentBody: apiResponse.msg,
                                                  buttonText: "YA",
                                                  tapButtonOk: () async {
                                                    await EasyLoading.show(
                                                      status: Strings.pleaseWait,
                                                      maskType: EasyLoadingMaskType.none,
                                                    );
                                                    ApiResponse apiResponse = await Api.submitBreak(
                                                      widget.isIn,
                                                      widget.branchModel.id,
                                                      widget.nik,
                                                      imageBase64!,
                                                      forceSubmit: 1,
                                                    );
                                                    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);
                                                          recallCamera();
                                                        },
                                                      );
                                                      return;
                                                    } else {
                                                      Navigator.pop(context);
                                                      AbsentSuccessModel absentSuccess =
                                                          apiResponse.data as AbsentSuccessModel;
                                                      Navigator.pushNamedAndRemoveUntil(
                                                        context,
                                                        Routes.absentSuccess,
                                                        (route) => false,
                                                        arguments: AbsentSuccessArguments(
                                                            absentSuccess: absentSuccess,
                                                            profil: widget.profile,
                                                            nik: widget.nik,
                                                            actionType: widget.actionType,
                                                            isIn: false,
                                                            shiftName: widget.shiftNameSelected,
                                                            shiftEnd: widget.shiftEndTime,
                                                            shiftStart: widget.shiftStartTime),
                                                      );
                                                      return;
                                                    }
                                                  },
                                                  isActiveCancelButton: true,
                                                  cancelButtonText: "Tidak",
                                                  tapButtonCancel: () {
                                                    Navigator.pop(context);
                                                    recallCamera();
                                                  },
                                                );
                                                return;
                                              }
                                              // END modal dialog konfirmasi kalau dia out of range
                                              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,
                                                  actionType: widget.actionType,
                                                  isIn: false,
                                                  shiftName: widget.shiftNameSelected,
                                                  shiftEnd: widget.shiftEndTime,
                                                  shiftStart: widget.shiftStartTime),
                                            );
                                          });
                                        }
                                      },
                                    ),
                                    SizedBox(
                                      height: AppMargin.m8,
                                    ),
                                    CustomButton(
                                      text: "Foto Ulang",
                                      colorButton: Colors.red,
                                      onTap: () {
                                        recallCamera();
                                      },
                                    )
                                  ],
                                ),
                              )
                            : Stack(
                                children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      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,
                        )
                      ],
                    ),
                  ),
                ],
              )
      ],
    );
  }
}

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.center,
                    maxLines: 2,
                    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(
              getAbsentText(widget.widget.isIn, widget.widget.actionType),
              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,
//             ),
//           ),
//         ],
//       ),
//     );
//   }
// }
