import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math' as math;
import 'package:absenkuv3/Bloc/Absensi/AbsensiBloc.dart';
import 'package:absenkuv3/Bloc/AuthBloc.dart';
import 'package:absenkuv3/Bloc/NavigatorBloc.dart';
import 'package:absenkuv3/Bloc/Shift/PilihShiftV2Bloc.dart';
import 'package:absenkuv3/Bloc/Shift/ShiftV2Bloc.dart';
import 'package:absenkuv3/Repository/Model/PageModel/mAbsensiPage.dart';
import 'package:absenkuv3/Repository/Model/mAbsensi.dart';
import 'package:absenkuv3/Repository/Model/mJadwalShift.dart';
import 'package:absenkuv3/Repository/Model/mLogin.dart';
import 'package:absenkuv3/Repository/sharedPreference.dart';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Modul/Absensi/BottomSheet.dart';
import 'package:absenkuv3/UI/Template/CameraIOS/cameraIOS.dart';
import 'package:absenkuv3/UI/Template/Camera/Bloc/CameraBloc.dart';
import 'package:absenkuv3/UI/Template/Camera/Model/CameraModel.dart';
import 'package:absenkuv3/UI/Template/Camera/UI/HalamanCamera.dart';
import 'package:absenkuv3/UI/Template/FaceRecognition/Bloc/FaceRecognitionBloc.dart'
    as recognition;
import 'package:absenkuv3/UI/Template/FaceRecognition/Bloc/FaceRegistrationBloc.dart';
import 'package:absenkuv3/UI/Template/FaceRecognition/UI/FaceRecognition.dart';
import 'package:absenkuv3/UI/Template/FaceRecognition/UI/FaceRegistration.dart';
import 'package:absenkuv3/UI/Template/buttonAbsensi.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:absenkuv3/UI/Template/templateButton.dart';
import 'package:absenkuv3/UI/Template/templateForm.dart';
import 'package:absenkuv3/UI/Template/templateIconInformation.dart';
import 'package:app_settings/app_settings.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../../Repository/Model/mFace.dart';
import '../../Template/CameraX/Bloc/FaceXBloc.dart';
import '../../Template/CameraX/Model/CameraXRespon.dart';
import 'KomponenAbsensi.dart';

class HalamanAbsensi extends StatefulWidget {
  @override
  _HalamanAbsensiState createState() => _HalamanAbsensiState();
}

class _HalamanAbsensiState extends State<HalamanAbsensi>
    with WidgetsBindingObserver {
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
  CameraModel? cameraModel;
  TextEditingController keterangan = new TextEditingController();
  late AbsensiHariIniRespon absensiHariIniRespon;
  DataAbsensi? dataHariIni;
  Lokasi? lokasi;
  JadwalAbsensi? jadwalAbsensi;
  StatusButtonAbsensi? statusButtonAbsensi;
  String? jamMasuk;
  String? jamPulang;
  String? jamKerja;
  String? jenisPeringatan;
  String? messagePeringatan;
  bool lifeCycleStateInit = true;
  bool? fleksible_jam_kerja;

  static const MethodChannel methodChannel = MethodChannel('absenku/camerax');
  static const EventChannel eventChannel =
      EventChannel('absenku/camerax/report');

  String _reportStatus = ' {"foto":"","matrix":""}';
  String? foto = "";
  String? matrix = "";
  var registrasi = false;
  String? jenis;
  Position? position;
  String? kamera2;

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    BlocProvider.of<AbsensiBloc>(context).add(CekAbsenEvent(context));
    BlocProvider.of<FaceXBloc>(context).add(InitialDialog(context));
    super.initState();
  }

  void didChangeAppLifecycleState(AppLifecycleState state) async {
    if (state == AppLifecycleState.resumed && lifeCycleStateInit) {
      BlocProvider.of<AbsensiBloc>(context).add(CekAbsenEvent(context));
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: keluar,
      child: Scaffold(
        key: scaffoldKey,
        backgroundColor: CustomStyle.backgroundDashboardColor,
        body: BlocBuilder<AuthBloc, LoginRespon>(
            builder: (BuildContext context, LoginRespon loginRespon) {
          return BlocListener<AbsensiBloc, AbsensiState>(
            listener: (BuildContext context, AbsensiState state) {
              if (state is PeringatanState) {
                jenisPeringatan = state.jenisPeringatan;
                messagePeringatan = state.message;
                popUpPeringatanV2(state.message, context);
              }
            },
            child: FutureBuilder<PageAbsensiModel>(
              future: PengaturanBahasa().absensi(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  return BlocListener<AbsensiBloc, AbsensiState>(
                    listener: (BuildContext context, AbsensiState state) {
                      if (state is PeringatanState &&
                          snapshot.connectionState == ConnectionState.done) {
                        jenisPeringatan = state.jenisPeringatan;
                        messagePeringatan = state.message;
                        popUpPeringatan(
                            state.message, context, snapshot.data!.absensi!);
                      }
                    },
                    child: BlocBuilder<AbsensiBloc, AbsensiState>(
                      builder: (context, state) {
                        Set<Marker> _markers = {};
                        Completer<GoogleMapController> _controller =
                            Completer();
                        CameraPosition _initPosition =
                            CameraPosition(target: LatLng(-6.9932, 110.4203));
                        if (state is AbsensiLoading) {
                          return Container(
                            height: double.infinity,
                            width: double.infinity,
                            child: Center(
                                child: CircularProgressIndicator(
                              strokeWidth: 8,
                            )),
                          );
                        } else if (state is AbsensiFailure) {
                          return Container(
                            height: double.infinity,
                            width: double.infinity,
                            decoration: CustomStyle.boxDecoration,
                            child: Center(
                              child: Text(state.errorMessage),
                            ),
                          );
                        } else if (state is AbsensiSuccess) {
                          animateCamera(_controller, state.position!);
                          _markers = state.markers;
                          absensiHariIniRespon = state.dataAbsen;
                          dataHariIni = absensiHariIniRespon.data!.dataAbsensi;
                          lokasi = absensiHariIniRespon.data!.lokasi;
                          jadwalAbsensi =
                              absensiHariIniRespon.data!.jadwalAbsensi;
                          statusButtonAbsensi =
                              absensiHariIniRespon.data!.statusButtonAbsensi;
                          fleksible_jam_kerja =
                              absensiHariIniRespon.data!.fleksible_jam_kerja;
                          print("TENGER ${fleksible_jam_kerja}");
                          jamMasuk = jadwalAbsensi!.jamKerja != null
                              ? jadwalAbsensi!.jamKerja!.jamMasuk
                              : '';
                          jamPulang = jadwalAbsensi!.jamKerja != null
                              ? jadwalAbsensi!.jamKerja!.jamPulang
                              : '';
                          jamKerja = '$jamMasuk - $jamPulang';

                          return Stack(
                            children: [
                              Container(
                                height: double.infinity - 30,
                                width: double.infinity,
                                child: GoogleMap(
                                  myLocationButtonEnabled: true,
                                  compassEnabled: true,
                                  zoomControlsEnabled: false,
                                  initialCameraPosition: _initPosition,
                                  mapType: MapType.normal,
                                  onMapCreated:
                                      (GoogleMapController controllers) {
                                    _controller.complete(controllers);
                                  },
                                  markers: _markers,
                                ),
                              ),
                              Align(
                                alignment: Alignment.topCenter,
                                child: Padding(
                                  padding:
                                      const EdgeInsets.fromLTRB(20, 40, 20, 0),
                                  child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      TombolIcon(
                                        icon: Icons.keyboard_arrow_left,
                                        onClick: () =>
                                            BlocProvider.of<NavigatorBloc>(
                                                    context)
                                                .add(NavigateRemoveToDashboard(
                                                    context)),
                                      ),
                                      TombolIcon(
                                        icon: Icons.refresh,
                                        onClick: () =>
                                            BlocProvider.of<AbsensiBloc>(
                                                    context)
                                                .add(CekAbsenEvent(context)),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              Align(
                                alignment: Alignment.bottomCenter,
                                child: Padding(
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 12),
                                  child: Container(
                                    child: Column(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: [
                                        Container(
                                          width: double.infinity,
                                          decoration: CustomStyle.boxDecoration,
                                          child: Padding(
                                            padding: const EdgeInsets.symmetric(
                                                horizontal: 0, vertical: 8),
                                            child: Column(
                                              children: [
                                                IconInformation(
                                                    icon: ValueImage.iconLokasi,
                                                    title: snapshot.data!
                                                        .absensi!.data!.lokasi,
                                                    subtitle:
                                                        lokasi!.ketLokasi ?? '',
                                                    sizeIcon: 33,
                                                    content: !lokasi!
                                                            .bolehAbsen!
                                                        ? snapshot
                                                            .data!
                                                            .absensi!
                                                            .messagePeringatan!
                                                            .tidakBolehAbsen
                                                        : null,
                                                    contentColor:
                                                        Colors.redAccent),
                                                Divider(),
                                                IconInformation(
                                                  icon: ValueImage.iconRadius,
                                                  title: snapshot.data!.absensi!
                                                      .data!.akurasi,
                                                  subtitle:
                                                      '${state.position!.accuracy.round().toString()} ${snapshot.data!.absensi!.data!.meter}',
                                                  sizeIcon: 29,
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        BlocBuilder<FaceXBloc, FaceXState>(
                                            builder: (BuildContext contextFaceX,
                                                FaceXState faceX) {
                                          if (faceX is FaceXStateInit) {
                                            return Container(
                                              width: double.infinity,
                                              decoration:
                                                  CustomStyle.boxDecoration,
                                              child: Padding(
                                                padding:
                                                    const EdgeInsets.all(12.0),
                                                child: Column(
                                                  children: [
                                                    Row(
                                                      children: [
                                                        statusButtonAbsensi!
                                                                    .toggleAbsenKerja! &&
                                                                fleksible_jam_kerja!
                                                            ? Expanded(
                                                                flex: 3,
                                                                child:
                                                                    IconInformation(
                                                                  icon: ValueImage
                                                                      .iconWaktu,
                                                                  title: jadwalAbsensi!
                                                                              .jenisJamKerja ==
                                                                          'reguler'
                                                                      ? '-'
                                                                      : jadwalAbsensi!
                                                                          .jamKerja!
                                                                          .keterangan,
                                                                  subtitle: jadwalAbsensi!
                                                                              .jenisJamKerja ==
                                                                          'reguler'
                                                                      ? '-'
                                                                      : jamKerja ??
                                                                          '',
                                                                  sizeIcon: 29,
                                                                ),
                                                              )
                                                            : Expanded(
                                                                flex: 3,
                                                                child:
                                                                    IconInformation(
                                                                  icon: ValueImage
                                                                      .iconWaktu,
                                                                  title: jadwalAbsensi!
                                                                          .jamKerja!
                                                                          .keterangan ??
                                                                      '',
                                                                  subtitle:
                                                                      jamKerja ??
                                                                          '',
                                                                  sizeIcon: 29,
                                                                ),
                                                              ),
                                                        Expanded(
                                                          flex: 2,
                                                          child: Column(
                                                            crossAxisAlignment:
                                                                CrossAxisAlignment
                                                                    .start,
                                                            children: [
                                                              Text(
                                                                jadwalAbsensi!
                                                                            .jamKerja !=
                                                                        null
                                                                    ? jadwalAbsensi!
                                                                        .jamKerja!
                                                                        .tanggal!
                                                                    : '',
                                                                style: CustomStyle
                                                                    .textStyleSmall,
                                                              ),
                                                              Text(
                                                                  absensiHariIniRespon
                                                                          .data!
                                                                          .statusButtonAbsensi!
                                                                          .keteranganButton ??
                                                                      '',
                                                                  style: TextStyle(
                                                                      fontWeight:
                                                                          FontWeight
                                                                              .w600,
                                                                      fontSize:
                                                                          CustomStyle.fontSizeSmall -
                                                                              1,
                                                                      color: Colors
                                                                          .redAccent)),
                                                            ],
                                                          ),
                                                        )
                                                      ],
                                                    ),
                                                    Divider(),
                                                    Row(
                                                      children: [
                                                        Expanded(
                                                          flex: 3,
                                                          child:
                                                              IconInformation(
                                                            icon: ValueImage
                                                                .iconJamKerja,
                                                            title: snapshot
                                                                .data!
                                                                .absensi!
                                                                .data!
                                                                .jamKerja,
                                                            subtitle:
                                                                "${dataHariIni!.jamMasuk} - ${dataHariIni!.jamPulang}",
                                                            sizeIcon: 28,
                                                          ),
                                                        ),
                                                        Expanded(
                                                          flex: 2,
                                                          child: ButtonAbsensi(
                                                            mulai: statusButtonAbsensi!
                                                                .toggleAbsenKerja,
                                                            enable: lokasi!
                                                                    .bolehAbsen! &&
                                                                statusButtonAbsensi!
                                                                    .enabledAbsenKerja!,
                                                            mulaiTitle: snapshot
                                                                .data!
                                                                .absensi!
                                                                .button!
                                                                .btnMasuk,
                                                            selesaiTitle:
                                                                snapshot
                                                                    .data!
                                                                    .absensi!
                                                                    .button!
                                                                    .btnPulang,
                                                            onClick: () async {
                                                              String? kamera =
                                                                  loginRespon
                                                                      .dataLogin!
                                                                      .kamera;
                                                              // if (kamera == '2') {
                                                              //   if (Platform.isIOS) {
                                                              //     kamera = '1';
                                                              //   }
                                                              // }
                                                              if (statusButtonAbsensi!
                                                                      .toggleAbsenKerja! &&
                                                                  fleksible_jam_kerja!) {
                                                                BlocProvider.of<
                                                                            ShiftV2Bloc>(
                                                                        context)
                                                                    .add(getJadwalShiftV2Event(
                                                                        context,
                                                                        '',
                                                                        lokasi!
                                                                            .lokasiKantor!));
                                                                showModalBottomSheet(
                                                                  context:
                                                                      context,
                                                                  isScrollControlled:
                                                                      true,
                                                                  showDragHandle:
                                                                      true,
                                                                  barrierColor: Colors
                                                                      .black
                                                                      .withOpacity(
                                                                          0.5),
                                                                  shape: RoundedRectangleBorder(
                                                                      borderRadius: BorderRadius.only(
                                                                          topLeft: Radius.circular(
                                                                              20),
                                                                          topRight:
                                                                              Radius.circular(20))),
                                                                  builder:
                                                                      (BuildContext
                                                                          context) {
                                                                    bool
                                                                        isKeyboardVisible =
                                                                        MediaQuery.of(context).viewInsets.bottom >
                                                                            0;
                                                                    return MultiBlocProvider(
                                                                      providers: [
                                                                        BlocProvider(
                                                                            create: (context) =>
                                                                                ShiftV2Bloc(ShiftProgressV2State())),
                                                                        BlocProvider(
                                                                            create: (context) =>
                                                                                PilihShiftV2Bloc(DataShift())),
                                                                      ],
                                                                      child:
                                                                          FractionallySizedBox(
                                                                        heightFactor: isKeyboardVisible
                                                                            ? 1.0
                                                                            : 0.75, // Set full height when keyboard is visible
                                                                        child:
                                                                            BottomSheetContent(
                                                                          login:
                                                                              loginRespon,
                                                                          lokasi:
                                                                              lokasi,
                                                                          position:
                                                                              state.position,
                                                                          jadwalAbsensi:
                                                                              jadwalAbsensi,
                                                                          jamKerja:
                                                                              jamKerja,
                                                                          ctx:
                                                                              context,
                                                                          lokasiKantor:
                                                                              lokasi!.lokasiKantor,
                                                                          faceX:
                                                                              faceX.faceRegistrationInfoRespon,
                                                                          redaksional: snapshot
                                                                              .data!
                                                                              .absensi!,
                                                                        ),
                                                                      ),
                                                                    );
                                                                  },
                                                                );
                                                              } else {
                                                                var status =
                                                                    await Permission
                                                                        .camera
                                                                        .status;
                                                                if (status
                                                                        .isDenied ||
                                                                    status
                                                                        .isPermanentlyDenied) {
                                                                  if (status
                                                                      .isPermanentlyDenied) {
                                                                    jenisPeringatan =
                                                                        "PermissionGPS";
                                                                    popUpPeringatan(
                                                                        snapshot
                                                                            .data!
                                                                            .absensi!
                                                                            .messagePeringatan!
                                                                            .kamera,
                                                                        context,
                                                                        snapshot
                                                                            .data!
                                                                            .absensi!);
                                                                  } else {
                                                                    await Permission
                                                                        .camera
                                                                        .request();
                                                                  }
                                                                } else {
                                                                  lifeCycleStateInit =
                                                                      false;
                                                                  if (kamera ==
                                                                      '1') {
                                                                    cameraModel = await Navigator.push<
                                                                            CameraModel>(
                                                                        context,
                                                                        MaterialPageRoute(
                                                                          builder: (_) => routeAbsensi(
                                                                              loginRespon.dataLogin!,
                                                                              statusButtonAbsensi!.toggleAbsenKerja! ? snapshot.data!.absensi!.button!.btnMasuk! : snapshot.data!.absensi!.button!.btnPulang!,
                                                                              snapshot.data!.absensi!.data!.registrasi!,
                                                                              snapshot.data!.absensi!.data!.titlePeringatan!,
                                                                              snapshot.data!.absensi!.button!.btnClose),
                                                                        ));
                                                                  } else if (kamera ==
                                                                      '2') {
                                                                    cameraModel = await routeCameraX(
                                                                        loginRespon
                                                                            .dataLogin!,
                                                                        statusButtonAbsensi!.toggleAbsenKerja!
                                                                            ? snapshot
                                                                                .data!.absensi!.button!.btnMasuk!
                                                                            : snapshot
                                                                                .data!.absensi!.button!.btnPulang!,
                                                                        state
                                                                            .position,
                                                                        kamera!,
                                                                        faceX
                                                                            .faceRegistrationInfoRespon,
                                                                        "Absensi",
                                                                        snapshot
                                                                            .data!
                                                                            .absensi!);
                                                                  } else {
                                                                    XFile? pickedFile = await ImagePicker().pickImage(
                                                                        source: ImageSource
                                                                            .camera,
                                                                        imageQuality:
                                                                            75,
                                                                        maxWidth:
                                                                            400);
                                                                    if (pickedFile !=
                                                                        null)
                                                                      cameraModel = CameraModel(
                                                                          base64Encode(File(pickedFile.path)
                                                                              .readAsBytesSync()),
                                                                          pickedFile
                                                                              .path);
                                                                  }
                                                                  if (cameraModel !=
                                                                      null)
                                                                    openDialog(
                                                                        statusButtonAbsensi!.toggleAbsenKerja!
                                                                            ? 'absen_masuk'
                                                                            : 'absen_pulang',
                                                                        state
                                                                            .position,
                                                                        context,
                                                                        snapshot
                                                                            .data!
                                                                            .absensi!,
                                                                        rotate: kamera ==
                                                                                '1'
                                                                            ? true
                                                                            : false);
                                                                }
                                                              }
                                                            },
                                                          ),
                                                        )
                                                      ],
                                                    ),
                                                    // Divider(),
                                                    // Row(
                                                    //   children: [
                                                    //     Expanded(
                                                    //       flex: 3,
                                                    //       child:
                                                    //           IconInformation(
                                                    //         icon: ValueImage
                                                    //             .iconJamIstirahat,
                                                    //         title: snapshot
                                                    //             .data!
                                                    //             .absensi!
                                                    //             .data!
                                                    //             .jamIstirahat!,
                                                    //         subtitle:
                                                    //             "${dataHariIni!.istirahatMulai} - ${dataHariIni!.istirahatSelesai}",
                                                    //         sizeIcon: 28,
                                                    //       ),
                                                    //     ),
                                                    //     Expanded(
                                                    //       flex: 2,
                                                    //       child: ButtonAbsensi(
                                                    //         mulai: statusButtonAbsensi!
                                                    //             .toggleAbsenIstirahat,
                                                    //         mulaiTitle: snapshot
                                                    //             .data!
                                                    //             .absensi!
                                                    //             .button!
                                                    //             .btnMulaiIst,
                                                    //         selesaiTitle: snapshot
                                                    //             .data!
                                                    //             .absensi!
                                                    //             .button!
                                                    //             .btnSelesaiIst,
                                                    //         enable: lokasi!
                                                    //                 .bolehAbsen! &&
                                                    //             statusButtonAbsensi!
                                                    //                 .enabledAbsenIstirahat!,
                                                    //         onClick: () async {
                                                    //           String? kamera =
                                                    //               loginRespon
                                                    //                   .dataLogin!
                                                    //                   .kamera;
                                                    //           // if (kamera == '2') {
                                                    //           //   if (Platform
                                                    //           //       .isIOS) {
                                                    //           //     kamera = '1';
                                                    //           //   }
                                                    //           // }
                                                    //           var status =
                                                    //               await Permission
                                                    //                   .camera
                                                    //                   .status;
                                                    //           if (status
                                                    //                   .isDenied ||
                                                    //               status
                                                    //                   .isPermanentlyDenied) {
                                                    //             if (status
                                                    //                 .isPermanentlyDenied) {
                                                    //               jenisPeringatan =
                                                    //                   "PermissionGPS";
                                                    //               popUpPeringatan(
                                                    //                   snapshot
                                                    //                       .data!
                                                    //                       .absensi!
                                                    //                       .messagePeringatan!
                                                    //                       .kamera,
                                                    //                   context,
                                                    //                   snapshot
                                                    //                       .data!
                                                    //                       .absensi!);
                                                    //             } else {
                                                    //               await Permission
                                                    //                   .camera
                                                    //                   .request();
                                                    //             }
                                                    //           } else {
                                                    //             lifeCycleStateInit =
                                                    //                 false;
                                                    //             if (kamera ==
                                                    //                 '1')
                                                    //               cameraModel = await Navigator.push<
                                                    //                       CameraModel>(
                                                    //                   context,
                                                    //                   MaterialPageRoute(
                                                    //                       builder: (_) => routeAbsensi(
                                                    //                           loginRespon.dataLogin!,
                                                    //                           statusButtonAbsensi!.toggleAbsenIstirahat! ? snapshot.data!.absensi!.button!.btnMulaiIst! : snapshot.data!.absensi!.button!.btnSelesaiIst!,
                                                    //                           snapshot.data!.absensi!.data!.registrasi!,
                                                    //                           snapshot.data!.absensi!.data!.titlePeringatan!,
                                                    //                           snapshot.data!.absensi!.button!.btnClose)));
                                                    //             else if (kamera ==
                                                    //                 '2') {
                                                    //               cameraModel = await routeCameraX(
                                                    //                   loginRespon
                                                    //                       .dataLogin!,
                                                    //                   statusButtonAbsensi!.toggleAbsenIstirahat!
                                                    //                       ? snapshot
                                                    //                           .data!
                                                    //                           .absensi!
                                                    //                           .button!
                                                    //                           .btnMulaiIst!
                                                    //                       : snapshot
                                                    //                           .data!
                                                    //                           .absensi!
                                                    //                           .button!
                                                    //                           .btnSelesaiIst!,
                                                    //                   state
                                                    //                       .position,
                                                    //                   kamera!,
                                                    //                   faceX
                                                    //                       .faceRegistrationInfoRespon,
                                                    //                   "Istirahat",
                                                    //                   snapshot
                                                    //                       .data!
                                                    //                       .absensi!);
                                                    //             } else {
                                                    //               XFile? pickedFile = await ImagePicker().pickImage(
                                                    //                   source: ImageSource
                                                    //                       .camera,
                                                    //                   imageQuality:
                                                    //                       75,
                                                    //                   maxWidth:
                                                    //                       400);
                                                    //               cameraModel = CameraModel(
                                                    //                   base64Encode(
                                                    //                       File(pickedFile!.path)
                                                    //                           .readAsBytesSync()),
                                                    //                   pickedFile
                                                    //                       .path);
                                                    //             }
                                                    //             if (cameraModel !=
                                                    //                 null)
                                                    //               openDialog(
                                                    //                   statusButtonAbsensi!
                                                    //                           .toggleAbsenIstirahat!
                                                    //                       ? 'istirahat_mulai'
                                                    //                       : 'istirahat_selesai',
                                                    //                   state
                                                    //                       .position,
                                                    //                   context,
                                                    //                   snapshot
                                                    //                       .data!
                                                    //                       .absensi!,
                                                    //                   rotate: kamera ==
                                                    //                           '1'
                                                    //                       ? true
                                                    //                       : false);
                                                    //           }
                                                    //         },
                                                    //       ),
                                                    //     ),
                                                    //   ],
                                                    // ),
                                                  
                                                  ],
                                                ),
                                              ),
                                            );
                                          } else {
                                            return CircularProgressIndicator(
                                              strokeWidth: 4,
                                            );
                                          }
                                        }),
                                        SizedBox(
                                          height: 10,
                                        )
                                      ],
                                    ),
                                  ),
                                ),
                              )
                            ],
                          );
                        } else {
                          return Container();
                        }
                      },
                    ),
                  );
                } else {
                  return Container();
                }
              },
            ),
          );
        }),
      ),
    );
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  Future<void> animateCamera(Completer<GoogleMapController> _controller,
      Position currentLocation) async {
    final GoogleMapController controller = await _controller.future;
    // print("lat :${currentLocation.latitude}");
    // print("long :${currentLocation.longitude}");
    CameraPosition _current = CameraPosition(
        target: LatLng(currentLocation.latitude, currentLocation.longitude),
        zoom: 17.151926040649414);
    controller.animateCamera(CameraUpdate.newCameraPosition(_current));
  }

  openDialog(String jenisAbsen, Position? position, BuildContext _context,
      Absensi redaksional,
      {bool rotate = true}) {
    final double mirror = math.pi;
    keterangan.text = '';
    Timer t = Timer(Duration(seconds: 60), () {
      Navigator.of(context).pushReplacementNamed('/');
    });
    showDialog(
        barrierDismissible: false,
        context: _context,
        builder: (BuildContext context) {
          return AlertDialog(
            shape: RoundedRectangleBorder(
                borderRadius:
                    BorderRadius.all(Radius.circular(CustomStyle.boxRadius))),
            content: SingleChildScrollView(
              reverse: true,
              child: Column(
                children: <Widget>[
                  Column(
                    children: [
                      rotate
                          ? Transform(
                              alignment: Alignment.center,
                              child: Platform.isAndroid
                                  ? Image.file(File(cameraModel!.path))
                                  : Image.memory(
                                      base64Decode(cameraModel!.base64)),
                              transform: Matrix4.rotationY(mirror))
                          : Platform.isAndroid
                              ? Image.file(File(cameraModel!.path))
                              : Image.memory(base64Decode(cameraModel!.base64)),
                      SizedBox(
                        height: 12,
                      ),
                      TemplateForm(
                        formHeight: CustomStyle.formHeight,
                        adaValidasi: true,
                        controller: keterangan,
                        color: Colors.grey[600],
                        titleText: redaksional.data!.keterangan,
                        radius: CustomStyle.formRadius,
                        hintText: redaksional.data!.keterangan,
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      TemplateButton(
                        onClick: () {
                          t.cancel();
                          BlocProvider.of<NavigatorBloc>(context)
                              .add(NavigatePop(context));
                        },
                        label: redaksional.button!.btnCancel,
                        color: Colors.transparent,
                        contentColor: CustomStyle.color1,
                        fontSize: CustomStyle.fontSizeNormal,
                        bold: true,
                      ),
                      TemplateButton(
                        onClick: () {
                          BlocProvider.of<NavigatorBloc>(_context)
                              .add(NavigatePop(_context));
                          BlocProvider.of<AbsensiBloc>(_context)
                              .add(TambahAbsenEvent(
                            _context,
                            scaffoldKey,
                            DataAbsensi(
                              jenisAbsen: jenisAbsen,
                              lokasiAbsen: lokasi!.namaLokasi,
                              latitude: position!.latitude.toString(),
                              longitude: position.longitude.toString(),
                              tipeAbsen: jadwalAbsensi!.jenisJamKerja,
                              kodeAbsen: jadwalAbsensi!.jamKerja!.kodeAbsensi,
                              ketKodeAbsen: jadwalAbsensi!.jamKerja!.ketKode,
                              jamKerja: jamKerja,
                              keteranganAbsen: keterangan.text,
                              foto: cameraModel!.base64,
                              tglJadwalAbsensi:
                                  jadwalAbsensi!.jamKerja!.tglJadwalAbsensi,
                              idMasterShift:
                                  jadwalAbsensi!.jamKerja!.idMasterShift,
                              fleksible_jam_kerja: false,
                            ),
                          ));
                        },
                        label: redaksional.button!.btnSubmit,
                        color: Colors.transparent,
                        contentColor: CustomStyle.color1,
                        fontSize: CustomStyle.fontSizeNormal,
                        bold: true,
                      )
                    ],
                  )
                ],
              ),
            ),
          );
        });
  }

  popUpPeringatan(String? message, _context, Absensi redaksional) {
    // print("ini message halaman ${message}");
    showDialog(
        barrierDismissible: false,
        context: _context,
        builder: (BuildContext context) {
          return WillPopScope(
            onWillPop: keluar,
            child: AlertDialog(
              shape: RoundedRectangleBorder(
                  borderRadius:
                      BorderRadius.all(Radius.circular(CustomStyle.boxRadius))),
              content: SingleChildScrollView(
                reverse: true,
                child: Column(
                  children: <Widget>[
                    Text(
                      message!,
                      style: TextStyle(color: Colors.redAccent),
                    ),
                    jenisPeringatan == 'PermissionGPS'
                        ? Column(
                            children: [
                              SizedBox(
                                height: 24,
                              ),
                              Align(
                                alignment: Alignment.centerRight,
                                child: GestureDetector(
                                  onTap: () async {
                                    BlocProvider.of<NavigatorBloc>(context)
                                        .add(NavigatePop(_context));
                                    AppSettings.openAppSettings();
                                    await sharedPreferences()
                                        .setInitialPermanentStatus(false);
                                  },
                                  child: Text(
                                    "Request Permission",
                                    style: TextStyle(
                                        color: CustomStyle.color1,
                                        fontWeight: FontWeight.w600,
                                        fontSize:
                                            CustomStyle.fontSizeSmall + 1),
                                  ),
                                ),
                              )
                            ],
                          )
                        : jenisPeringatan == 'errorData'
                            ? Column(
                                children: [
                                  SizedBox(
                                    height: 24,
                                  ),
                                  Align(
                                    alignment: Alignment.centerRight,
                                    child: GestureDetector(
                                      onTap: () {
                                        BlocProvider.of<NavigatorBloc>(context)
                                            .add(NavigatePop(_context));
                                        BlocProvider.of<NavigatorBloc>(context)
                                            .add(NavigateRemoveToDashboard(
                                                context));
                                      },
                                      child: Text(
                                        redaksional
                                            .messagePeringatan!.hubungiAdmin!,
                                        style: TextStyle(
                                            color: CustomStyle.color1,
                                            fontWeight: FontWeight.w600,
                                            fontSize:
                                                CustomStyle.fontSizeSmall + 1),
                                      ),
                                    ),
                                  )
                                ],
                              )
                            : Container(),
                  ],
                ),
              ),
            ),
          );
        });
  }

  popUpPeringatanV2(String? message, _context) {
    showDialog(
        barrierDismissible: false,
        context: _context,
        builder: (BuildContext context) {
          return WillPopScope(
            onWillPop: keluar,
            child: AlertDialog(
              shape: RoundedRectangleBorder(
                  borderRadius:
                      BorderRadius.all(Radius.circular(CustomStyle.boxRadius))),
              content: SingleChildScrollView(
                reverse: true,
                child: Column(
                  children: <Widget>[
                    Text(
                      message!,
                      style: TextStyle(color: Colors.redAccent),
                    ),
                  ],
                ),
              ),
            ),
          );
        });
  }

  Future<bool> keluar() async {
    BlocProvider.of<NavigatorBloc>(context)
        .add(NavigateRemoveToDashboard(context));
    BlocProvider.of<AbsensiBloc>(context).add(LoadingEvent(context));

    return false;
  }

  routeAbsensi(
      DataLogin dataLogin, String konteks, String registrasi, title, btnLabel) {
    if (dataLogin.lockFaceRecognition! &&
        (dataLogin.faceData == null || dataLogin.faceData == '')) {
      return BlocProvider(
          create: (BuildContext context) =>
              FaceRegistrationBloc(InitializeProgress()),
          child: FaceRegistration(registrasi, title, btnLabel));
    } else if (dataLogin.lockFaceRecognition! &&
        (dataLogin.faceData != null || dataLogin.faceData != '')) {
      return BlocProvider(
          create: (BuildContext context) =>
              recognition.FaceRecognitionBloc(recognition.InitializeProgress()),
          child: FaceRecognition(konteks));
    } else {
      return BlocProvider(
        create: (BuildContext context) =>
            CameraBloc(InitializeCameraProgress()),
        child: CameraApp(konteks, true),
      );
    }
  }

  routeCameraX(
      DataLogin dataLogin,
      String konteks,
      Position? position,
      String kamera,
      List<DataFaceRegistrationInfo>? peringatan,
      String jenis,
      Absensi redaksional) {
    if (Platform.isIOS) {
      _startCameraXActivity(position, kamera, false, jenis, redaksional);
    } else {
      if (dataLogin.lockFaceRecognition! &&
          (dataLogin.faceData == null || dataLogin.faceData == '')) {
        _startCameraXFace(
            true, position, kamera, peringatan, jenis, redaksional);
      } else if (dataLogin.lockFaceRecognition! &&
          (dataLogin.faceData != null || dataLogin.faceData != '')) {
        _startCameraXFace(
            false, position, kamera, peringatan, jenis, redaksional);
      } else {
        _startCameraXActivity(position, kamera, false, jenis, redaksional);
      }
    }
  }

  Future<void> _startCameraXActivity(Position? position, String kamera,
      bool kameraBelakang, String jenis, Absensi redaksional) async {
    print('jenissss');
    if (Platform.isIOS) {
      Navigator.push(
              context, MaterialPageRoute(builder: (_) => CameraIosPage(1)))
          .then((value) {
        if (value != null) {
          String _base64Image = base64Encode(value);
          setState(() {
            this.position = position;
            this.kamera2 = "camera";
            this.jenis = jenis;
            // registrasi = register;
          });
          cameraModel = CameraModel(_base64Image, "");
          // this.kamera2 = "camera";
          if (jenis == "Absensi") {
            openDialog(
                statusButtonAbsensi!.toggleAbsenKerja!
                    ? 'absen_masuk'
                    : 'absen_pulang',
                this.position,
                context,
                redaksional,
                rotate: false);
          } else {
            openDialog(
                statusButtonAbsensi!.toggleAbsenIstirahat!
                    ? 'istirahat_mulai'
                    : 'istirahat_selesai',
                this.position,
                context,
                redaksional,
                rotate: false);
          }
        }
      });
    } else {
      setState(() {
        this.position = position;
        this.kamera2 = "camera";
        this.jenis = jenis;
        // registrasi = register;
      });
      try {
        // print('masukkkkkkreceiveBroadcastStream');
        eventChannel.receiveBroadcastStream().listen((event) {
          setState(() {
            _reportStatus = event.toString();
            CameraXRespon cameraXRespon = cameraXResponFromJson(_reportStatus);

            foto = cameraXRespon.foto;
            matrix = cameraXRespon.matrix;
            // print('foto hasil '+foto.toString());
            cameraModel =
                CameraModel(base64Encode(File(foto!).readAsBytesSync()), foto!);
            var fotoBase64 = base64Encode(File(foto!).readAsBytesSync());
            List<double> numbersList = [];
            try {
              numbersList = matrix
                  .toString()
                  .replaceAll('[', '') // Menghapus karakter "[" dari string
                  .replaceAll(']', '') // Menghapus karakter "]" dari string
                  .split(
                      ',') // Memisahkan angka-angka berdasarkan tanda koma ","
                  .map((String number) => double.parse(
                      number.trim())) // Mengubah setiap string menjadi double
                  .toList(); // Mengonversi hasil ke dalam List<double>
            } catch (e) {
              numbersList = [];
            }

            if (registrasi) {
              BlocProvider.of<FaceXBloc>(context).add(registrasiEvent(
                  context, scaffoldKey, numbersList, fotoBase64, false));
            } else {
              if (jenis == "Absensi") {
                openDialog(
                    statusButtonAbsensi!.toggleAbsenKerja!
                        ? 'absen_masuk'
                        : 'absen_pulang',
                    this.position,
                    context,
                    redaksional,
                    rotate: this.kamera2 == 'face' ? true : false);
              } else {
                openDialog(
                    statusButtonAbsensi!.toggleAbsenIstirahat!
                        ? 'istirahat_mulai'
                        : 'istirahat_selesai',
                    this.position,
                    context,
                    redaksional,
                    rotate: this.kamera2 == 'face' ? true : false);
              }
            }
          });
        }, onError: _onError);
        if(jenis == "Absensi"){
          await methodChannel.invokeMethod('startCameraXActivity', {
            "kameraBelakang": kameraBelakang,
            "header_text": statusButtonAbsensi!.toggleAbsenKerja!
                ? redaksional.button!.btnMasuk
                : redaksional.button!.btnPulang
          });
        }else{
          await methodChannel.invokeMethod('startCameraXActivity', {
            "kameraBelakang": kameraBelakang,
            "header_text": statusButtonAbsensi!.toggleAbsenIstirahat!
                ? redaksional.button!.btnMulaiIst
                : redaksional.button!.btnSelesaiIst
          });
        }
      } on PlatformException catch (e) {
        // debugPrint("Failed to Invoke: '${e.message}'.");
      }
    }
  }

  Future<void> _startCameraXFace(
      bool register,
      Position? position,
      String kamera,
      List<DataFaceRegistrationInfo>? peringatan,
      String jenis,
      Absensi redaksional) async {
    LoginRespon data = await sharedPreferences().getUserData();
    String bahasa = await sharedPreferences().getBahasa();
    // print(" ini bahasa ${bahasa}");
    double cosineThreshold = data.dataLogin!.cosineThreshold!;
    double l2Threshold = data.dataLogin!.l2Threshold!;
    String faceData = "";
    setState(() {
      this.position = position;
      this.kamera2 = "face";
      registrasi = register;
      this.jenis = jenis;
    });
    if (register) {
      faceData = "";
    } else {
      String faceDataString = data.dataLogin!.faceData!;
      String modifiedString =
          faceDataString.replaceAll('[', '').replaceAll(']', '');
      faceData = modifiedString;
    }
    String stringPeringatan = "";
    for (int i = 0; i < peringatan!.length; i++) {
      stringPeringatan = stringPeringatan + peringatan[i].isi.toString() + "| ";
    }

    try {
      eventChannel.receiveBroadcastStream().listen((event) {
        setState(() {
          _reportStatus = event.toString();
          CameraXRespon cameraXRespon = cameraXResponFromJson(_reportStatus);

          foto = cameraXRespon.foto;
          matrix = cameraXRespon.matrix;

          cameraModel =
              CameraModel(base64Encode(File(foto!).readAsBytesSync()), foto!);
          var fotoBase64 = base64Encode(File(foto!).readAsBytesSync());
          List<double> numbersList = [];
          try {
            numbersList = matrix
                .toString()
                .replaceAll('[', '') // Menghapus karakter "[" dari string
                .replaceAll(']', '') // Menghapus karakter "]" dari string
                .split(',') // Memisahkan angka-angka berdasarkan tanda koma ","
                .map((String number) => double.parse(
                    number.trim())) // Mengubah setiap string menjadi double
                .toList(); // Mengonversi hasil ke dalam List<double>
          } catch (e) {
            numbersList = [];
          }

          if (registrasi) {
            BlocProvider.of<FaceXBloc>(context).add(registrasiEvent(
                context, scaffoldKey, numbersList, fotoBase64, false));
          } else {
            if (jenis == "Absensi") {
              openDialog(
                  statusButtonAbsensi!.toggleAbsenKerja!
                      ? 'absen_masuk'
                      : 'absen_pulang',
                  this.position,
                  context,
                  redaksional,
                  rotate: this.kamera2 == 'face' ? true : false);
            } else {
              openDialog(
                  statusButtonAbsensi!.toggleAbsenIstirahat!
                      ? 'istirahat_mulai'
                      : 'istirahat_selesai',
                  this.position,
                  context,
                  redaksional,
                  rotate: this.kamera2 == 'face' ? true : false);
            }
          }
        });
      }, onError: _onError);

      await methodChannel.invokeMethod('startFaceCameraXActivity', {
        'matrix': faceData,
        'register': register,
        'peringatan': stringPeringatan.toString(),
        'cosineThreshold': cosineThreshold,
        'l2Threshold': l2Threshold,
        'language': bahasa,
        'header_text': statusButtonAbsensi!.toggleAbsenKerja!
            ? redaksional.button!.btnMasuk
            : redaksional.button!.btnPulang,
      });
    } on PlatformException catch (e) {
      // debugPrint("Failed to Invoke: '${e.message}'.");
    }
  }

  void _onError(Object error) {
    setState(() {
      _reportStatus = 'Camera status: ${error.toString()}';
    });
  }
}
