import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:absenkuv3/Bloc/Aktivitas/AbsensiAktivitasBloc.dart';
import 'package:absenkuv3/Bloc/Aktivitas/EditAktivitasBloc.dart';
import 'package:absenkuv3/Bloc/AuthBloc.dart';
import 'package:absenkuv3/Bloc/NavigatorBloc.dart';
import 'package:absenkuv3/Repository/Model/PageModel/mAktivitasPage.dart';
import 'package:absenkuv3/Repository/Model/mAktivitas.dart';
import 'package:absenkuv3/Repository/Model/mLembur.dart' as mLembur;
import 'package:absenkuv3/Repository/Model/mLogin.dart';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Modul/Absensi/KomponenAbsensi.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/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 'dart:math' as math;
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../Template/CameraX/Model/CameraXRespon.dart';

class HalamanEditAktivitas extends StatefulWidget {
  var data;
  HalamanEditAktivitas(this.data);
  @override
  _HalamanEditAktivitasState createState() => _HalamanEditAktivitasState();
}

class _HalamanEditAktivitasState extends State<HalamanEditAktivitas>
    with WidgetsBindingObserver {
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  CameraModel? cameraModel;
  TextEditingController keterangan = new TextEditingController();
  CekLokasiRespon? dataRespon;
  String? jenisPeringatan;
  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;
  Position? position;
  String? kamera2;

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    BlocProvider.of<AbsensiAktivitasBloc>(context)
        .add(CekAbsenAktivitasEvent(context));
    BlocProvider.of<EditAktivitasBloc>(context)
        .add(GetEditAktivitas(widget.data[0]));
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: scaffoldKey,
        body: BlocBuilder<AuthBloc, LoginRespon>(
            builder: (BuildContext context, LoginRespon loginRespon) {
          return BlocListener<AbsensiAktivitasBloc, AbsensiAktivitasState>(
            listener: (BuildContext context, AbsensiAktivitasState state) {
              if (state is PeringatanState) {
                jenisPeringatan = state.jenisPeringatan;
                popUpPeringatanV2(state.message, context);
              }
            },
            child: FutureBuilder<PageAktivitasModel>(
                future: PengaturanBahasa().aktivitas(),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    return BlocConsumer<AbsensiAktivitasBloc,
                        AbsensiAktivitasState>(
                      listener: (context, state) {
                        if (state is PeringatanState) {
                          jenisPeringatan = state.jenisPeringatan;
                          popUpPeringatan(state.message, context);
                        }
                      },
                      builder: (context, state) {
                        Set<Marker> _markers = {};
                        Completer<GoogleMapController> _controller =
                            Completer();
                        CameraPosition _initPosition =
                            CameraPosition(target: LatLng(-6.9932, 110.4203));
                        if (state is AbsensiAktivitasLoading) {
                          return Container(
                            height: double.infinity,
                            width: double.infinity,
                            child: Center(
                                child: CircularProgressIndicator(
                              strokeWidth: 8,
                            )),
                          );
                        } else if (state is AbsensiAktivitasFailure) {
                          return Container(
                            height: double.infinity,
                            width: double.infinity,
                            decoration: CustomStyle.boxDecoration,
                            child: Center(
                              child: Text(state.errorMessage),
                            ),
                          );
                        } else if (state is AbsensiAktivitasSuccess) {
                          animateCamera(_controller, state.position!);
                          _markers = state.markers;
                          dataRespon = state.cekLokasiRespon;

                          return BlocBuilder<EditAktivitasBloc,
                                  EditAktivitasState>(
                              builder: (context, aktivitas) {
                            if (aktivitas is EditAktivitasSuccess) {
                              keterangan.text = aktivitas
                                      .aktivitasRespon.data![0].keterangan ??
                                  '';
                            }
                            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(NavigatePop(context)),
                                        ),
                                        TombolIcon(
                                          icon: Icons.refresh,
                                          onClick: () => BlocProvider.of<
                                                  AbsensiAktivitasBloc>(context)
                                              .add(CekAbsenAktivitasEvent(
                                                  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.iconWaktu,
                                                    title: snapshot
                                                        .data!
                                                        .menuAktivitas!
                                                        .data!
                                                        .tanggal,
                                                    subtitle:
                                                        dataRespon!.tanggal,
                                                    sizeIcon: 29,
                                                  ),
                                                  Divider(),
                                                  IconInformation(
                                                    icon: ValueImage.iconLokasi,
                                                    title: snapshot
                                                        .data!
                                                        .menuAktivitas!
                                                        .data!
                                                        .lokasi,
                                                    subtitle: dataRespon!
                                                            .cekLokasi!
                                                            .ketLokasi ??
                                                        '',
                                                    sizeIcon: 33,
                                                  ),
                                                  Divider(),
                                                  IconInformation(
                                                    icon: ValueImage.iconRadius,
                                                    title: snapshot
                                                        .data!
                                                        .menuAktivitas!
                                                        .data!
                                                        .akurasi,
                                                    subtitle:
                                                        '${state.position!.accuracy.round().toString()} ${snapshot.data!.menuAktivitas!.data!.meter}',
                                                    sizeIcon: 29,
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                          SizedBox(
                                            height: 10,
                                          ),
                                          Container(
                                            width: double.infinity,
                                            decoration:
                                                CustomStyle.boxDecoration,
                                            child: Padding(
                                              padding:
                                                  const EdgeInsets.all(12.0),
                                              child: Row(
                                                children: [
                                                  Expanded(
                                                    flex: 4,
                                                    child: Row(
                                                      children: [
                                                        Expanded(
                                                          flex: 1,
                                                          child: Container(
                                                            width: 35,
                                                            height: 35,
                                                            child: Image.asset(
                                                                ValueImage
                                                                    .iconLembur),
                                                          ),
                                                        ),
                                                        SizedBox(
                                                          width: 10,
                                                        ),
                                                        Expanded(
                                                          flex: 5,
                                                          child: Text(
                                                            snapshot
                                                                .data!
                                                                .menuAktivitas!
                                                                .data!
                                                                .header!,
                                                            overflow:
                                                                TextOverflow
                                                                    .ellipsis,
                                                            style: TextStyle(
                                                                fontSize:
                                                                    CustomStyle
                                                                            .fontSizeSmall -
                                                                        1,
                                                                color: CustomStyle
                                                                    .fontColorGrey),
                                                          ),
                                                        )
                                                      ],
                                                    ),
                                                  ),
                                                  SizedBox(
                                                    width: 12,
                                                  ),
                                                  BlocBuilder<AuthBloc,
                                                      LoginRespon>(
                                                    builder:
                                                        (BuildContext context,
                                                            LoginRespon
                                                                loginRespon) {
                                                      return Expanded(
                                                        flex: 3,
                                                        child: ButtonAbsensi(
                                                          mulai: true,
                                                          mulaiTitle: snapshot
                                                              .data!
                                                              .menuAktivitas!
                                                              .button!
                                                              .btnAktivitas,
                                                          enable: true,
                                                          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!
                                                                        .menuAktivitas!
                                                                        .data!
                                                                        .messagePermission!,
                                                                    context);
                                                              } else {
                                                                await Permission
                                                                    .camera
                                                                    .request();
                                                              }
                                                            } else {
                                                              lifeCycleStateInit =
                                                                  false;
                                                              if (kamera == '1')
                                                                cameraModel = await Navigator.push<
                                                                        CameraModel>(
                                                                    context,
                                                                    MaterialPageRoute(
                                                                        builder: (_) =>
                                                                            BlocProvider(
                                                                              create: (BuildContext context) => CameraBloc(InitializeCameraProgress()),
                                                                              child: CameraApp(
                                                                                snapshot.data!.menuAktivitas!.data!.absensiAktivitas,
                                                                                false,
                                                                                changeCamera: true,
                                                                                defaultCamera: 'back',
                                                                              ),
                                                                            )));
                                                              else if (kamera ==
                                                                  '2') {
                                                                cameraModel = await routeCameraX(
                                                                    state
                                                                        .position,
                                                                    kamera!,
                                                                    snapshot
                                                                        .data!
                                                                        .menuAktivitas!);
                                                              } 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(
                                                                    state
                                                                        .position,
                                                                    context,
                                                                    snapshot
                                                                        .data!
                                                                        .menuAktivitas!,
                                                                    rotate: kamera ==
                                                                                '1' &&
                                                                            cameraModel!.cameraId ==
                                                                                1
                                                                        ? true
                                                                        : false);
                                                            }
                                                          },
                                                        ),
                                                      );
                                                    },
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                          SizedBox(
                                            height: 10,
                                          )
                                        ],
                                      ),
                                    ),
                                  ),
                                )
                              ],
                            );
                          });
                        } else {
                          return Container();
                        }
                      },
                    );
                  } else {
                    return CircularProgressIndicator(strokeWidth: 8);
                  }
                }),
          );
        }));
  }

  popUpPeringatanV2(String? message, _context) {
    showDialog(
        barrierDismissible: false,
        context: _context,
        builder: (BuildContext context) {
          return WillPopScope(
            onWillPop: keluarV2,
            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),
                    ),
                  ],
                ),
              ),
            ),
          );
        });
  }

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

  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(Position? position, _context, MenuAktivitas redaksional,
      {bool rotate = true}) {
    // print("ROTATE $rotate");
    final double mirror = math.pi;
    keterangan.text = '';
    showDialog(
        context: _context,
        builder: (BuildContext context) {
          return Form(
            key: formKey,
            child: 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: 56,
                          adaValidasi: true,
                          controller: keterangan,
                          color: Colors.grey[600],
                          titleText: redaksional.data!.keterangan,
                          radius: CustomStyle.formRadius,
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        TemplateButton(
                          onClick: () => BlocProvider.of<NavigatorBloc>(context)
                              .add(NavigatePop(context)),
                          label: redaksional.button!.btnCancel,
                          color: Colors.transparent,
                          contentColor: CustomStyle.color1,
                          fontSize: CustomStyle.fontSizeNormal,
                          bold: true,
                        ),
                        TemplateButton(
                          onClick: () {
                            if (formKey.currentState!.validate()) {
                              BlocProvider.of<NavigatorBloc>(_context)
                                  .add(NavigatePop(_context));
                              BlocProvider.of<AbsensiAktivitasBloc>(_context)
                                  .add(EditAbsenAktivitasEvent(
                                      _context,
                                      widget.data[1],
                                      scaffoldKey,
                                      mLembur.DataAbsensi(
                                          idAktivitas: widget.data[0],
                                          lokasiAbsen:
                                              dataRespon!.cekLokasi!.namaLokasi,
                                          latitude:
                                              position!.latitude.toString(),
                                          longitude:
                                              position.longitude.toString(),
                                          keteranganAbsen: keterangan.text,
                                          foto: cameraModel!.base64)));
                            }
                          },
                          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: () {
                                    BlocProvider.of<NavigatorBloc>(context)
                                        .add(NavigatePop(_context));
                                    AppSettings.openAppSettings();
                                  },
                                  child: Text(
                                    "Request Permission",
                                    style: TextStyle(
                                        color: CustomStyle.color1,
                                        fontWeight: FontWeight.w600,
                                        fontSize:
                                            CustomStyle.fontSizeSmall + 1),
                                  ),
                                ),
                              )
                            ],
                          )
                        : Container(),
                  ],
                ),
              ),
            ),
          );
        });
  }

  Future<bool> keluar() async {
    /*if(jenisPeringatan=='PermissionGPS')
      BlocProvider.of<NavigatorBloc>(context)
          .add(NavigateRemoveToDashboard(context));
    else{
      BlocProvider.of<NavigatorBloc>(context)
          .add(NavigatePop(context));
      BlocProvider.of<NavigatorBloc>(context)
          .add(NavigatePop(context));
    }*/
    BlocProvider.of<NavigatorBloc>(context).add(NavigatePop(context));
    BlocProvider.of<NavigatorBloc>(context).add(NavigatePop(context));
    return false;
  }

  Future<bool> keluarV2() async {
    BlocProvider.of<NavigatorBloc>(context)
        .add(NavigateRemoveToDashboard(context));
    return false;
  }

  routeCameraX(Position? position, String kamera, MenuAktivitas redaksional) {
    _startCameraXActivity(position, kamera, true, redaksional);
  }

  Future<void> _startCameraXActivity(Position? position, String kamera,
      bool kameraBelakang, MenuAktivitas redaksional) async {
    print("ini kamrea belakang $kameraBelakang");
    if (Platform.isIOS) {
      Navigator.push(
              context, MaterialPageRoute(builder: (_) => CameraIosPage(0)))
          .then((value) {
        if (value != null) {
          String _base64Image = base64Encode(value);
          setState(() {
            this.position = position;
            this.kamera2 = "camera";
          });
          cameraModel = CameraModel(_base64Image, "");
          openDialog(position, context, redaksional, rotate: false);
        }
      });
    } else {
      setState(() {
        this.position = position;
        this.kamera2 = kamera;
        // registrasi = register;
      });
      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!);
            openDialog(position, context, redaksional, rotate: false);
          });
        }, onError: _onError);
        await methodChannel.invokeMethod('startCameraXActivity', {
          "kameraBelakang": kameraBelakang,
          'header_text': 'Foto Laporan Kinerja',
        });
      } on PlatformException catch (e) {
        debugPrint("Failed to Invoke: '${e.message}'.");
      }
    }
  }

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