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/CustomFunction.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/mFace.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/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/CameraIOS/cameraIOS.dart';
import 'package:absenkuv3/UI/Template/CameraX/Bloc/FaceXBloc.dart';
import 'package:absenkuv3/UI/Template/CameraX/Model/CameraXRespon.dart';
import 'package:absenkuv3/UI/Template/FaceRecognition/Bloc/FaceRegistrationBloc.dart';
import 'package:absenkuv3/UI/Template/FaceRecognition/Bloc/FaceRecognitionBloc.dart'
    as recognition;
import 'package:absenkuv3/UI/Template/FaceRecognition/UI/FaceRecognition.dart';
import 'package:absenkuv3/UI/Template/FaceRecognition/UI/FaceRegistration.dart';
import 'package:absenkuv3/UI/Template/dialog/dialogConfirmationv2.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:absenkuv3/UI/Template/templateButton.dart';
import 'package:absenkuv3/UI/Template/templateForm.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 'package:shimmer/shimmer.dart';
import '../../../Repository/Model/mAbsensi.dart';

class BottomSheetContent extends StatefulWidget {
  final DataShift? dataShift;
  final LoginRespon? login;
  final Lokasi? lokasi;
  final Position? position;
  final JadwalAbsensi? jadwalAbsensi;
  final String? jamKerja;
  final BuildContext? ctx;
  final List<DataFaceRegistrationInfo>? faceX;
  final bool? lokasiKantor;
  final Absensi? redaksional;
  BottomSheetContent({
    this.dataShift,
    this.login,
    this.lokasi,
    this.position,
    this.jadwalAbsensi,
    this.jamKerja,
    this.ctx,
    this.faceX,
    this.lokasiKantor,
    this.redaksional
  });

  @override
  State<BottomSheetContent> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<BottomSheetContent> {
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
  CameraModel? cameraModel;
  TextEditingController keterangan = new TextEditingController();
  TextEditingController keyword = TextEditingController();
  late AbsensiHariIniRespon absensiHariIniRespon;
  DataAbsensi? dataHariIni;
  JadwalAbsensi? jadwalAbsensi;
  StatusButtonAbsensi? statusButtonAbsensi;
  String? jamMasuk;
  String? jamPulang;
  String? jenisPeringatan;
  String? messagePeringatan;
  String? shiftSebelumnya;
  String? attStatus;
  String? attNote;
  List<DataShift>? jadwalShift;
  DataShift? pilihanShift;
  bool lifeCycleStateInit = true;
  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;
  String? kamera2;
  int? count;
  String searchQuery = '';
  List<DataShift> filteredShifts = [];
  List<DataShift> allShifts = [];
  @override
  void initState() {
    count = 0;
    BlocProvider.of<ShiftV2Bloc>(context)
        .add(getJadwalShiftV2Event(context, '', widget.lokasiKantor!));
    keyword.addListener(cariListener);
    // allShifts = jadwalShift!;
    filteredShifts = [];
    super.initState();
  }

  cariListener() {
    if (keyword.text.length > 1) {
      count = 0;
      setState(() {
        print(keyword.text);
        filteredShifts = allShifts.where((shift) {
          return shift.namaShift!
              .toLowerCase()
              .contains(keyword.text.toLowerCase());
        }).toList();
      });
      // BlocProvider.of<ShiftV2Bloc>(context).add(
      //     getJadwalShiftV2Event(context, keyword.text, widget.lokasiKantor!));
    }
  }

  void _filterShifts(String query) {
    setState(() {
      searchQuery = query;
      filteredShifts = allShifts.where((shift) {
        return shift.namaShift!.toLowerCase().contains(query.toLowerCase());
      }).toList();
    });
  }

  void _handleRadioValueChange(DataShift? value) {
    // print(value!.button);
    if (value!.button!) {
      BlocProvider.of<PilihShiftV2Bloc>(context).add(SetShift(value!));
    }
    // BlocProvider.of<PilihShiftV2Bloc>(context)
    //     .add(SetShift(value!));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      body:Stack(
        children: [
          BlocBuilder<ShiftV2Bloc, ShiftV2State>(
            builder: (context, stateShift) {
              return Container(
                width: MediaQuery.of(context).size.width,
                // color: Colors.red,
                child: BlocBuilder<PilihShiftV2Bloc, DataShift>(
                  builder: (BuildContext cons, DataShift dataShift) {
                    if (stateShift is getListJadwalShiftSuccessState) {
                      allShifts = stateShift.dataShift!.dataShift!;
                      filteredShifts = allShifts.where((shift) {
                        return shift.namaShift!
                            .toLowerCase()
                            .contains(searchQuery.toLowerCase());
                      }).toList();
                    }
                    return Column(
                      children: [
                        stateShift is getListJadwalShiftSuccessState
                            ? stateShift.dataShift!.jadwalShift!.status == true
                                ? 
                                Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Container(
                                      padding:
                                          EdgeInsets.only(top: 5, bottom: 5),
                                      decoration: BoxDecoration(
                                          color: CustomStyle.color1,
                                          borderRadius: new BorderRadius.all(
                                            Radius.circular(10),
                                          )),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Padding(
                                            padding: const EdgeInsets.only(
                                                left: 10.0,
                                                right: 10.0,
                                                top: 5,
                                                bottom: 5),
                                            child: Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment
                                                      .spaceBetween,
                                              children: [
                                                Column(
                                                  children: [
                                                    Container(
                                                      width:
                                                          MediaQuery.of(context)
                                                                      .size
                                                                      .width /
                                                                  2 -
                                                              50,
                                                      child: Text(
                                                        widget.redaksional!.data!.jadwalKerjaAndaSaatIni.toString(),
                                                        style: TextStyle(
                                                            color: Colors.white,
                                                            fontSize: CustomStyle
                                                                .fontSizeSubTitle,
                                                            fontWeight:
                                                                FontWeight
                                                                    .w600),
                                                        maxLines: 2,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                                Column(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.end,
                                                  children: [
                                                    Text(
                                                      stateShift
                                                          .dataShift!
                                                          .jadwalShift!
                                                          .jadwalDefault!
                                                          .namaShift!,
                                                      style: TextStyle(
                                                          color: Colors.white,
                                                          fontSize: CustomStyle
                                                              .fontSizeNormal,
                                                          fontWeight:
                                                              FontWeight.w700),
                                                    ),
                                                    SizedBox(
                                                      height: 5,
                                                    ),
                                                    Padding(
                                                      padding:
                                                          const EdgeInsets.only(
                                                              left: 10.0),
                                                      child: Text(
                                                        stateShift
                                                                .dataShift!
                                                                .jadwalShift!
                                                                .jadwalDefault!
                                                                .jamMasuk! +
                                                            ' - ' +
                                                            stateShift
                                                                .dataShift!
                                                                .jadwalShift!
                                                                .jadwalDefault!
                                                                .jamPulang!,
                                                        style: TextStyle(
                                                            color: Colors.white,
                                                            fontSize: CustomStyle
                                                                .fontSizeNormal),
                                                      ),
                                                    ),
                                                    SizedBox(
                                                      height: 5,
                                                    ),
                                                  ],
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  )
                                : Container()
                            : Container(
                                height: MediaQuery.of(context).size.height / 10,
                                width: MediaQuery.of(context).size.width - 30,
                                child: Container(
                                  height:
                                      MediaQuery.of(context).size.height / 20,
                                  width: MediaQuery.of(context).size.width - 60,
                                  child: Shimmer.fromColors(
                                    baseColor: Colors.grey[300]!,
                                    highlightColor: Colors.white,
                                    period: Duration(seconds: 2),
                                    child: Card(),
                                  ),
                                ),
                              ),
                        SizedBox(
                          height: 5,
                        ),
                        Align(
                          alignment: Alignment.topLeft,
                          child: Padding(
                            padding: EdgeInsets.fromLTRB(10, 0, 0, 10),
                            child: Text(widget.redaksional!.data!.pilihJamKerja.toString(),
                                style: TextStyle(
                                    fontSize: CustomStyle.fontSizeSubTitle,
                                    fontWeight: FontWeight.w600)),
                          ),
                        ),
                        Padding(
                          padding:
                              EdgeInsets.only(left: 10, bottom: 10, right: 10),
                          child: Container(
                            width: MediaQuery.of(context).size.width - 10,
                            child: TemplateForm(
                                fontSize: CustomStyle.fontSizeSmall,
                                prefixIcon: Icon(
                                  Icons.search,
                                  size: 20,
                                ),
                                hintText: widget.redaksional!.data!.hintSemuaJamKerja.toString(),
                                controller: keyword,
                                color: CustomStyle.fontColorBlack,
                                formHeight: 40,
                                radius: CustomStyle.formRadius,
                                bottomMargin: 0,
                                onChange: (newValue) {
                                  setState(() {
                                    searchQuery = newValue.toString();
                                    filteredShifts = allShifts.where((shift) {
                                      return shift.namaShift!
                                          .toLowerCase()
                                          .contains(searchQuery.toLowerCase());
                                    }).toList();
                                  });
                                },
                                buttonEnd: keyword.text.length != 0
                                    ? GestureDetector(
                                        onTap: () {
                                          keyword.clear();
                                          setState(() {
                                            searchQuery = '';
                                            filteredShifts =
                                                allShifts.where((shift) {
                                              return shift.namaShift!
                                                  .toLowerCase()
                                                  .contains(searchQuery
                                                      .toLowerCase());
                                            }).toList();
                                          });
                                        },
                                        child: Icon(
                                          Icons.close,
                                          color: Colors.red,
                                          size: 22,
                                        ))
                                    : Container()),
                          ),
                        ),
                        Divider(
                          indent: 5,
                          thickness: 1,
                          endIndent: 5,
                          color: Colors.grey,
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        Expanded(
                          child: stateShift is getListJadwalShiftSuccessState
                              ? 
                              filteredShifts.isNotEmpty ?
                              Container(
                                  width: MediaQuery.of(context).size.width - 30,
                                  child: ListView.builder(
                                      padding: EdgeInsets.only(bottom: 80.0),
                                      physics: AlwaysScrollableScrollPhysics(),
                                      itemCount: filteredShifts.length,
                                      itemBuilder:
                                          (BuildContext context, index) {
                                        if (filteredShifts[index].active ==
                                                true &&
                                            count == 0) {
                                          _handleRadioValueChange(
                                              filteredShifts[index]);
                                          count = 1;
                                        }
                                        return filteredShifts[index].active ==
                                                true
                                            ? 
                                            Column(
                                                children: [
                                                  GestureDetector(
                                                    onTap: () {
                                                      _handleRadioValueChange(
                                                          filteredShifts[
                                                              index]);
                                                    },
                                                    child: Container(
                                                      decoration: BoxDecoration(
                                                          border: Border.all(
                                                              color: filteredShifts[
                                                                          index] ==
                                                                      dataShift
                                                                  ? CustomStyle
                                                                      .color1
                                                                  : Color(
                                                                      0xffE0E0E0)),
                                                          borderRadius:
                                                              new BorderRadius
                                                                  .all(
                                                            Radius.circular(10),
                                                          )),
                                                      child: Padding(
                                                        padding:
                                                            const EdgeInsets
                                                                .only(
                                                                top: 10.0,
                                                                bottom: 10),
                                                        child: Row(
                                                          mainAxisAlignment:
                                                              MainAxisAlignment
                                                                  .spaceBetween,
                                                          children: [
                                                            Padding(
                                                              padding:
                                                                  const EdgeInsets
                                                                      .only(
                                                                      left:
                                                                          25.0),
                                                              child: Column(
                                                                crossAxisAlignment:
                                                                    CrossAxisAlignment
                                                                        .start,
                                                                children: [
                                                                  Text(
                                                                    filteredShifts[index]
                                                                            .kodeShift! +
                                                                        ' - ' +
                                                                        filteredShifts[index]
                                                                            .namaShift!,
                                                                    style: TextStyle(
                                                                        color: Colors
                                                                            .black,
                                                                        fontSize:
                                                                            16,
                                                                        fontWeight:
                                                                            FontWeight.w700),
                                                                  ),
                                                                  filteredShifts[index]
                                                                              .jamMasuk! !=
                                                                          ''
                                                                      ? SizedBox(
                                                                          height:
                                                                              5,
                                                                        )
                                                                      : SizedBox(),
                                                                  filteredShifts[index]
                                                                              .jamMasuk! !=
                                                                          ''
                                                                      ? Text(
                                                                          filteredShifts[index].jamMasuk! +
                                                                              ' - ' +
                                                                              filteredShifts[index].jamPulang!,
                                                                          style: TextStyle(
                                                                              color: CustomStyle.fontColorGrey,
                                                                              fontSize: 14),
                                                                        )
                                                                      : SizedBox(),
                                                                  filteredShifts[index]
                                                                              .namaKlien! !=
                                                                          ''
                                                                      ? Column(
                                                                        children: [
                                                                          SizedBox(height: 5,),
                                                                          Text(filteredShifts[index]
                                                                                  .namaKlien!,
                                                                              style: TextStyle(
                                                                                  color: CustomStyle.fontColorGrey,
                                                                                  fontSize: 14),
                                                                            ),
                                                                        ],
                                                                      )
                                                                      : SizedBox()
                                                                ],
                                                              ),
                                                            ),
                                                            Padding(
                                                              padding:
                                                                  const EdgeInsets
                                                                      .only(
                                                                      right:
                                                                          10.0),
                                                              child: Radio<
                                                                  DataShift?>(
                                                                toggleable:
                                                                    true,
                                                                materialTapTargetSize:
                                                                    MaterialTapTargetSize
                                                                        .padded,
                                                                value:
                                                                    filteredShifts[
                                                                        index],
                                                                activeColor:
                                                                    CustomStyle
                                                                        .color1,
                                                                groupValue:
                                                                    dataShift,
                                                                onChanged:
                                                                    _handleRadioValueChange,
                                                              ),
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                    ),
                                                  ),
                                                  SizedBox(
                                                    height: 5,
                                                  )
                                                ],
                                              )
                                            : filteredShifts[index].button ==
                                                    true
                                                ? Column(
                                                    children: [
                                                      GestureDetector(
                                                        onTap: () {
                                                          _handleRadioValueChange(
                                                              filteredShifts[
                                                                  index]);
                                                        },
                                                        child: Container(
                                                          decoration:
                                                              BoxDecoration(
                                                                  border: Border.all(
                                                                      color: filteredShifts[index] ==
                                                                              dataShift
                                                                          ? CustomStyle
                                                                              .color1
                                                                          : Color(
                                                                              0xffE0E0E0)),
                                                                  borderRadius:
                                                                      new BorderRadius
                                                                          .all(
                                                                    Radius
                                                                        .circular(
                                                                            10),
                                                                  )),
                                                          child: Padding(
                                                            padding:
                                                                const EdgeInsets
                                                                    .only(
                                                                    top: 10.0,
                                                                    bottom: 10),
                                                            child: Row(
                                                              mainAxisAlignment:
                                                                  MainAxisAlignment
                                                                      .spaceBetween,
                                                              children: [
                                                                Padding(
                                                                  padding:
                                                                      const EdgeInsets
                                                                          .only(
                                                                          left:
                                                                              25.0),
                                                                  child: Column(
                                                                    crossAxisAlignment:
                                                                        CrossAxisAlignment
                                                                            .start,
                                                                    children: [
                                                                      Text(
                                                                        filteredShifts[index].kodeShift! +
                                                                            ' - ' +
                                                                            filteredShifts[index].namaShift!,
                                                                        style: TextStyle(
                                                                            color: Colors
                                                                                .black,
                                                                            fontSize:
                                                                                16,
                                                                            fontWeight:
                                                                                FontWeight.w700),
                                                                      ),
                                                                      filteredShifts[index].jamMasuk! !=
                                                                              ''
                                                                          ? SizedBox(
                                                                              height: 5,
                                                                            )
                                                                          : SizedBox(),
                                                                      filteredShifts[index].jamMasuk! !=
                                                                              ''
                                                                          ? Text(
                                                                              filteredShifts[index].jamMasuk! + ' - ' + stateShift.dataShift!.dataShift![index].jamPulang!,
                                                                              style: TextStyle(color: CustomStyle.fontColorGrey, fontSize: 14),
                                                                            )
                                                                          : SizedBox(),
                                                                      filteredShifts[index]
                                                                              .namaKlien! !=
                                                                          ''
                                                                      ? Column(
                                                                        children: [
                                                                          SizedBox(height: 5,),
                                                                          Text(filteredShifts[index]
                                                                                  .namaKlien!,
                                                                              style: TextStyle(
                                                                                  color: CustomStyle.fontColorGrey,
                                                                                  fontSize: 14),
                                                                            ),
                                                                        ],
                                                                      )
                                                                      : SizedBox()
                                                                    ],
                                                                  ),
                                                                ),
                                                                Padding(
                                                                  padding:
                                                                      const EdgeInsets
                                                                          .only(
                                                                          right:
                                                                              10.0),
                                                                  child: Radio<
                                                                      DataShift?>(
                                                                    toggleable:
                                                                        true,
                                                                    materialTapTargetSize:
                                                                        MaterialTapTargetSize
                                                                            .padded,
                                                                    value: filteredShifts[
                                                                        index],
                                                                    activeColor:
                                                                        CustomStyle
                                                                            .color1,
                                                                    groupValue:
                                                                        dataShift,
                                                                    onChanged:
                                                                        _handleRadioValueChange,
                                                                  ),
                                                                ),
                                                              ],
                                                            ),
                                                          ),
                                                        ),
                                                      ),
                                                      SizedBox(
                                                        height: 5,
                                                      )
                                                    ],
                                                  )
                                                : Column(
                                                    children: [
                                                      GestureDetector(
                                                        onTap: () {
                                                          _handleRadioValueChange(
                                                              filteredShifts[
                                                                  index]);
                                                        },
                                                        child: Container(
                                                          decoration:
                                                              BoxDecoration(
                                                                  border: Border.all(
                                                                      color: Color(
                                                                          0xffE0E0E0)),
                                                                  borderRadius:
                                                                      new BorderRadius
                                                                          .all(
                                                                    Radius
                                                                        .circular(
                                                                            10),
                                                                  )),
                                                          child: Padding(
                                                            padding:
                                                                const EdgeInsets
                                                                    .only(
                                                                    top: 10.0,
                                                                    bottom: 10),
                                                            child: Row(
                                                              mainAxisAlignment:
                                                                  MainAxisAlignment
                                                                      .spaceBetween,
                                                              children: [
                                                                Padding(
                                                                  padding:
                                                                      const EdgeInsets
                                                                          .only(
                                                                          left:
                                                                              25.0),
                                                                  child: Column(
                                                                    crossAxisAlignment:
                                                                        CrossAxisAlignment
                                                                            .start,
                                                                    children: [
                                                                      Text(
                                                                        filteredShifts[index].kodeShift! +
                                                                            ' - ' +
                                                                            filteredShifts[index].namaShift!,
                                                                        style: TextStyle(
                                                                            color: Color(
                                                                                0xffe0e0e0),
                                                                            fontSize:
                                                                                16,
                                                                            fontWeight:
                                                                                FontWeight.bold),
                                                                      ),
                                                                      SizedBox(
                                                                        height:
                                                                            5,
                                                                      ),
                                                                      Text(
                                                                        filteredShifts[index].jamMasuk! +
                                                                            ' - ' +
                                                                            filteredShifts[index].jamPulang!,
                                                                        style: TextStyle(
                                                                            color:
                                                                                Color(0xffe0e0e0),
                                                                            fontSize: 14),
                                                                      ),
                                                                      filteredShifts[index]
                                                                              .namaKlien! !=
                                                                          ''
                                                                      ? Column(
                                                                        children: [
                                                                          SizedBox(height: 5,),
                                                                          Text(filteredShifts[index]
                                                                                  .namaKlien!,
                                                                              style: TextStyle(
                                                                                  color: Color(0xffe0e0e0),
                                                                                  fontSize: 14),
                                                                            ),
                                                                        ],
                                                                      )
                                                                      : SizedBox()
                                                                    ],
                                                                  ),
                                                                ),
                                                                Padding(
                                                                  padding:
                                                                      const EdgeInsets
                                                                          .only(
                                                                          right:
                                                                              10.0),
                                                                  child: Radio<
                                                                      DataShift?>(
                                                                    materialTapTargetSize:
                                                                        MaterialTapTargetSize
                                                                            .padded,
                                                                    value: filteredShifts[
                                                                        index],
                                                                    activeColor:
                                                                        Color(
                                                                            0x00000000),
                                                                    autofocus:
                                                                        false,
                                                                    groupValue:
                                                                        dataShift,
                                                                    onChanged:
                                                                        _handleRadioValueChange,
                                                                  ),
                                                                ),
                                                              ],
                                                            ),
                                                          ),
                                                        ),
                                                      ),
                                                      SizedBox(
                                                        height: 5,
                                                      )
                                                    ],
                                                  );
                                      }),
                                )
                              :Center(child: Text('No shifts available'))
                              : Container(
                                  height:
                                      MediaQuery.of(context).size.height * 0.35,
                                  padding: EdgeInsets.all(16),
                                  child: Center(
                                    child: CircularProgressIndicator(),
                                  )),
                        ),
                        
                        Container(
                          height: MediaQuery.of(context).size.height * 0.08,
                          width: MediaQuery.of(context).size.width,
                          color: Colors.white24,
                          child: Center(
                            child: Padding(
                              padding: const EdgeInsets.only(
                                  left: 10.0, right: 10.0),
                              child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    GestureDetector(
                                      onTap: () {
                                        BlocProvider.of<NavigatorBloc>(context)
                                            .add(NavigatePop(context));
                                      },
                                      child: Container(
                                        width:
                                            MediaQuery.of(context).size.width /
                                                2.5,
                                        height:
                                            MediaQuery.of(context).size.height *
                                                0.05,
                                        decoration: BoxDecoration(
                                            border: Border.all(
                                                width: 1,
                                                color: CustomStyle.color1),
                                            color: Colors.white12,
                                            borderRadius: BorderRadius.all(
                                                Radius.circular(20))),
                                        child: Center(
                                            child: Text(
                                          widget.redaksional!.button!.btnModalBatal.toString(),
                                          style: TextStyle(
                                              color: CustomStyle.color1,
                                              fontSize: 15,
                                              fontWeight: FontWeight.bold),
                                        )),
                                      ),
                                    ),
                                    GestureDetector(
                                      onTap: () async {
                                        if (dataShift.button == true) {
                                          if (stateShift.dataShift!.jadwalShift!
                                                  .status ==
                                              false) {
                                            attStatus = '';
                                            attNote = '';
                                            shiftSebelumnya = '';
                                            print("masuk1");
                                          } else if (stateShift
                                                  .dataShift!
                                                  .jadwalShift!
                                                  .jadwalDefault!
                                                  .idMasterShift !=
                                              dataShift.idMasterShift) {
                                            shiftSebelumnya = 
                                            stateShift
                                                    .dataShift!
                                                    .jadwalShift!
                                                    .jadwalDefault!
                                                    .kodeShift! +
                                                '-' +
                                                stateShift
                                                    .dataShift!
                                                    .jadwalShift!
                                                    .jadwalDefault!
                                                    .namaShift! +
                                                '#';
                                            print("masuk2");
                                            print(shiftSebelumnya);
                                            // attStatus = '';
                                            // attNote = '';
                                          } else {
                                            shiftSebelumnya = '';
                                            // attStatus = stateShift
                                            //     .dataShift!
                                            //     .jadwalShift!
                                            //     .jadwalDefault!
                                            //     .attStatus;
                                            // attNote = stateShift
                                            //     .dataShift!
                                            //     .jadwalShift!
                                            //     .jadwalDefault!
                                            //     .attNote;
                                          }

                                          String? kamera =
                                              widget.login!.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(
                                                  "Anda belum menyetujui penggunaan Camera untuk absensi",
                                                  context);
                                            } else {
                                              await Permission.camera.request();
                                            }
                                          } else {
                                            lifeCycleStateInit = false;
                                            if (kamera == '1')
                                              cameraModel = await Navigator
                                                  .push<CameraModel>(
                                                context,
                                                MaterialPageRoute(
                                                    builder: (_) =>
                                                        routeAbsensi(
                                                            widget.login!
                                                                .dataLogin!,
                                                            widget.redaksional!.button!.btnMasuk!,
                                                            widget.redaksional!.data!.registrasi!,
                                                            widget.redaksional!.data!.titlePeringatan!,
                                                            widget.redaksional!.button!.btnClose
                                                            )),
                                              );
                                            else if (kamera == '2') {
                                              cameraModel = await routeCameraX(
                                                widget.login!.dataLogin!,
                                                'Absensi Masuk',
                                                widget.position,
                                                kamera!,
                                                widget.faceX,
                                                "Absensi",
                                                dataShift,
                                                shiftSebelumnya,
                                                widget.redaksional!
                                              );
                                            } 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) {
                                              print("masuk10");
                                              print(shiftSebelumnya);
                                              openDialog(
                                                'absen_masuk',
                                                widget.position,
                                                widget.ctx!,
                                                dataShift,
                                                widget.redaksional!,
                                                rotate: kamera == '1'
                                                    ? true
                                                    : false,
                                                shiftSebelumnya:
                                                    shiftSebelumnya!,
                                                // attStatus: attStatus!,
                                                // attNote: attNote!,
                                              );// Use context for popping the screen
                                            }
                                          }
                                        } else {
                                          showSnackBarDelayed(
                                              null,
                                              widget.redaksional!.data!.jamKerjaBelumDipilih,
                                              context);
                                        }
                                      },
                                      child: Container(
                                        width:
                                            MediaQuery.of(context).size.width /
                                                2.5,
                                        height:
                                            MediaQuery.of(context).size.height *
                                                0.05,
                                        decoration: BoxDecoration(
                                          color: dataShift == DataShift()
                                              ? Colors.grey
                                              : CustomStyle.color1,
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(20)),
                                        ),
                                        child: Center(
                                          child: Text(widget.redaksional!.button!.btnModalLanjutkan.toString(),
                                              style: TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 15,
                                                  fontWeight: FontWeight.bold)),
                                        ),
                                      ),
                                    )
                                  ]),
                            ),
                          ),
                        )
                      ],
                    );
                  },
                ),
              );
            },
          ),
        ],
      )
    );
  }

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

  openDialog(String jenisAbsen, Position? position, BuildContext _context,
      DataShift? pilihanShift,Absensi redaksional,
      {bool rotate = true,
      String shiftSebelumnya = '',
      String attStatus = '',
      String attNote = ''}) {
    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: () {
                        print(shiftSebelumnya);
                          BlocProvider.of<NavigatorBloc>(_context)
                              .add(NavigatePop(_context));
                          BlocProvider.of<AbsensiBloc>(_context)
                              .add(TambahAbsenEvent(
                            _context,
                            scaffoldKey,
                            DataAbsensi(
                              jenisAbsen: jenisAbsen,
                              lokasiAbsen: widget.lokasi!.namaLokasi,
                              latitude: widget.position!.latitude.toString(),
                              longitude: widget.position!.longitude.toString(),
                              tipeAbsen: 'shift',
                              kodeAbsen: pilihanShift!.kodeShift,
                              ketKodeAbsen: pilihanShift.namaShift,
                              jamKerja: pilihanShift.jamMasuk! +
                                  ' - ' +
                                  pilihanShift.jamPulang!,
                              keteranganAbsen: keterangan.text,
                              foto: cameraModel!.base64,
                              tglJadwalAbsensi: widget
                                  .jadwalAbsensi!.jamKerja!.tglJadwalAbsensi,
                              idMasterShift: pilihanShift.idMasterShift,
                              fleksible_jam_kerja: true,
                              idKlien: pilihanShift.idKlien,
                              namaKlien: pilihanShift.namaKlien,
                              // toleransiTerlambat:
                              //     pilihanShift.toleransiTerlambat.toString(),
                              shiftSebelumnya: shiftSebelumnya,
                              // attStatus: attStatus,
                              // attNote: attNote,
                            ),
                          ));
                        },
                        label: redaksional.button!.btnSubmit,
                        color: Colors.transparent,
                        contentColor: CustomStyle.color1,
                        fontSize: CustomStyle.fontSizeNormal,
                        bold: true,
                      )
                    ],
                  )
                ],
              ),
            ),
          );
        });
  }

  popUpPeringatan(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),
                    ),
                    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(
                                        "Silahkan hubungi admin",
                                        style: TextStyle(
                                            color: CustomStyle.color1,
                                            fontWeight: FontWeight.w600,
                                            fontSize:
                                                CustomStyle.fontSizeSmall + 1),
                                      ),
                                    ),
                                  )
                                ],
                              )
                            : Container(),
                  ],
                ),
              ),
            ),
          );
        });
  }

  Future<bool> keluar() async {
    BlocProvider.of<NavigatorBloc>(context)
        .add(NavigateRemoveToDashboard(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,
      DataShift dataShift,
      String? shiftSebelumnya,
      Absensi? redaksional) {
    if(Platform.isIOS){
      _startCameraXActivity(position, kamera, false, jenis, dataShift,shiftSebelumnya,redaksional);
    }else{
    if (dataLogin.lockFaceRecognition! &&
        (dataLogin.faceData == null || dataLogin.faceData == '')) {
      _startCameraXFace(true, position, kamera, peringatan, jenis, dataShift,shiftSebelumnya,redaksional);
    } else if (dataLogin.lockFaceRecognition! &&
        (dataLogin.faceData != null || dataLogin.faceData != '')) {
      _startCameraXFace(false, position, kamera, peringatan, jenis, dataShift,shiftSebelumnya,redaksional);
    } else {
      _startCameraXActivity(position, kamera, false, jenis, dataShift,shiftSebelumnya,redaksional);
    }
    }
  }

  Future<void> _startCameraXActivity(Position? position, String kamera,
      bool kameraBelakang, String jenis, DataShift dataShift,String? ShiftSebelumnya,Absensi? redaksional) async {
    if(Platform.isIOS){
      Navigator.push(context, MaterialPageRoute(builder: (_)=> CameraIosPage(1)))
          .then((value) {
        if(value != null){
          String _base64Image = base64Encode(value);
          setState(() {
            position = position;
            kamera2 = "camera";
            jenis = jenis;
            pilihanShift = dataShift;
            shiftSebelumnya = ShiftSebelumnya;
          });
          cameraModel = CameraModel(_base64Image, "");
          openDialog('absen_masuk', widget.position, context, pilihanShift,redaksional!,shiftSebelumnya: shiftSebelumnya!);
        }
      });
    }else{
    setState(() {
      position = position;
      kamera2 = "camera";
      jenis = jenis;
      pilihanShift = dataShift;
      shiftSebelumnya = ShiftSebelumnya;
    });
    
    try {
      // eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
      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,true));
            } else {
              openDialog('absen_masuk', widget.position, context, pilihanShift,redaksional!,
              rotate: kamera2 == 'face' ? true : false,shiftSebelumnya: shiftSebelumnya!);
            }
          });
        }, onError: _onError);
        
      await methodChannel.invokeMethod('startCameraXActivity', {
        "kameraBelakang": kameraBelakang,
        "header_text":  redaksional!.button!.btnMasuk!,
      });
    
    } on PlatformException catch (e) {
      debugPrint("Failed to Invoke: '${e.message}'.");
    }
    }
  }

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

    try {
      // eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
      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,true));
          } else {
            openDialog('absen_masuk', widget.position, context, pilihanShift,redaksional!,
              rotate: kamera2 == 'face' ? true : false,shiftSebelumnya: shiftSebelumnya!);
            // 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': redaksional!.button!.btnMasuk!,
      });
    } on PlatformException catch (e) {
      debugPrint("Failed to Invoke: '${e.message}'.");
    }
  }

  // void _onEvent(Object? 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('[', '')
  //           .replaceAll(']', '')
  //           .split(',')
  //           .map((String number) => double.parse(number.trim()))
  //           .toList();
  //     } catch (e) {
  //       numbersList = [];
  //       print("error $e");
  //     }
  //     print("ininumberlist ${numbersList}");
  //     if (registrasi) {
  //       BlocProvider.of<FaceXBloc>(context).add(
  //           registrasiEvent(context, scaffoldKey, numbersList, fotoBase64));
  //     } else {
  //       openDialog('absen_masuk', widget.position, context, pilihanShift,
  //           rotate: kamera2 == 'face' ? true : false,shiftSebelumnya: shiftSebelumnya!);
  //       // if (jenis == "Absensi") {
  //       //   openDialog(
  //       //       statusButtonAbsensi!.toggleAbsenKerja!
  //       //           ? 'absen_masuk'
  //       //           : 'absen_pulang',
  //       //       widget.position,
  //       //       context,
  //       //       DataShift(),
  //       //       rotate: kamera2 == 'face' ? true : false);
  //       // } else {
  //       //   openDialog(
  //       //       statusButtonAbsensi!.toggleAbsenIstirahat!
  //       //           ? 'istirahat_mulai'
  //       //           : 'istirahat_selesai',
  //       //       widget.position,
  //       //       context,
  //       //       DataShift(),
  //       //       rotate: kamera2 == 'face' ? true : false);
  //       // }
  //     }
  //   });
  //   print("Foto12: $foto");
  //   print("Matrix12: $matrix");
  //   print("INIREPORT ${_reportStatus.toString()}");
  //   debugPrint(_reportStatus);
  // }

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