// ignore_for_file: sized_box_for_whitespace

import 'dart:async';
import 'dart:io';
import 'package:excelso_attendance/helper/arguments/error_args.dart';
import 'package:excelso_attendance/helper/widget_responsive.dart';
import 'package:excelso_attendance/main.dart';
import 'package:excelso_attendance/resource/routes.dart';
import 'package:excelso_attendance/resource/strings.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'dart:typed_data';

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

class AbsentCameraView extends StatefulWidget {
  const AbsentCameraView(
      {super.key, required this.outletName, required this.isIn});

  final String outletName;
  final bool isIn;

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

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

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

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

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

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

  void initStateFunc() {
    getCameraDescrption().then((value) {
      cameras = value;
      if (cameras!.length > 1) {
        _cameraDescription = cameras![1];
      } else {
        if (cameras!.isNotEmpty) {
          _cameraDescription = cameras![0];
        } else {
          _cameraDescription = null;
        }
      }
      // _cameraDescription = cameras![1];

      if (_cameraDescription != null) {
        _controller = CameraController(
          // Get a specific camera from the list of available cameras.
          _cameraDescription!,
          // Define the resolution to use.
          ResolutionPreset.medium,
        );
        setState(() {
          _initializeControllerFuture = _controller!.initialize();
        });
      }
    }).catchError((e) {
      if (e is CameraException) {
        switch (e.code) {
          case 'CameraAccessDenied':
            // setState(() {
            //   isPermissionAccept = false;
            // });
            Navigator.pushNamedAndRemoveUntil(
              context,
              Routes.errorWidget,
              (route) => false,
              arguments: ErrorWidgetArguments(
                errorMessage: Strings.cameraNotActive,
              ),
            );
          default:
            // setState(() {
            //   errorCamera = "$e";
            // });
            if (debug) {
              // ignore: avoid_print
              print("CAMERA PERMISSION PROB ERROR: $e");
            }
        }
      }
    });
  }

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

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

  Column bodyWidget(Size size) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // (isPermissionAccept) ?
        (_initializeControllerFuture != null)
            ? FutureBuilder(
                future: _initializeControllerFuture,
                builder: ((context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    return Stack(
                      children: [
                        Container(
                          width: size.width,
                          height: size.height,
                          padding: EdgeInsets.only(
                              top: AppPadding.safeAreaTop(context) + 40),
                          child: (pictureIsTaken)
                              ? (isPhone)
                                  ? Image.file(
                                      File(imagePathPhone!),
                                      fit: BoxFit.fill,
                                    )
                                  : Image.memory(
                                      imagePath!,
                                      // fit: BoxFit.fill,
                                    )
                              : CameraPreview(
                                  _controller!,
                                ),
                        ),
                        Container(
                          width: size.width,
                          height: size.height,
                          padding: EdgeInsets.only(
                              top: AppPadding.safeAreaTop(context) + 40),
                          child: Image(
                            fit: BoxFit.fill,
                            image: AssetImage(Assets.frameOverlay),
                          ),
                        ),
                        Container(
                          width: size.width,
                          height: size.height,
                          child: Column(
                            children: [
                              Container(
                                height: AppPadding.safeAreaTop(context) + 60,
                                width: double.infinity,
                                decoration: BoxDecoration(
                                  borderRadius: const BorderRadius.only(
                                    bottomRight: Radius.circular(20),
                                    bottomLeft: Radius.circular(20),
                                  ),
                                  color: ColorManager.primary,
                                ),
                                child: Container(
                                  padding: EdgeInsets.symmetric(
                                      horizontal: AppPadding.p20),
                                  margin: EdgeInsets.only(
                                    top: AppPadding.safeAreaTop(context),
                                  ),
                                  child: Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      GestureDetector(
                                        onTap: () {
                                          Navigator.pop(context);
                                        },
                                        child: const Icon(
                                          Icons.arrow_back,
                                          color: Colors.white,
                                          size: 24,
                                        ),
                                      ),
                                      Container(
                                        margin: EdgeInsets.only(
                                          left: AppMargin.m16,
                                        ),
                                        child: Text(
                                          "Verifikasi Wajah",
                                          style: getBoldStyle(
                                            color: Colors.white,
                                            fontSize: 17,
                                          ),
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              ),
                              const SizedBox(
                                height: 15,
                              ),
                              WidgetAbsentAndTime(
                                isIn: widget.isIn,
                                outletName: widget.outletName,
                              ),
                              const Spacer(),
                              (pictureIsTaken)
                                  ? Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: [
                                        Container(
                                          width: 100,
                                          child: CustomButton(
                                            text: "Submit",
                                            onTap: () {
                                              Navigator.pushNamed(
                                                context,
                                                Routes.absentSuccess,
                                              );
                                            },
                                          ),
                                        ),
                                        Container(
                                          width: 100,
                                          margin: const EdgeInsets.only(
                                            top: 10,
                                          ),
                                          child: GestureDetector(
                                            onTap: () {
                                              setState(() {
                                                pictureIsTaken = false;
                                              });
                                            },
                                            child: CustomButton(
                                              text: "Foto Ulang",
                                              colorButton: ColorManager.grey,
                                            ),
                                          ),
                                        ),
                                      ],
                                    )
                                  : Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        // GestureDetector(
                                        //   onTap: () {
                                        //     if (flashMode ==
                                        //         FlashMode.always) {
                                        //       flashMode = FlashMode.off;
                                        //     } else {
                                        //       flashMode = FlashMode.always;
                                        //     }
                                        //     setState(() {
                                        //       _controller!
                                        //           .setFlashMode(flashMode);
                                        //     });
                                        //   },
                                        //   child: Icon(
                                        //     Icons.flash_auto,
                                        //     size: 35,
                                        //     color: ColorManager.primary,
                                        //   ),
                                        // ),
                                        const SizedBox(
                                          width: 35,
                                        ),
                                        const SizedBox(
                                          width: 20,
                                        ),
                                        InkWell(
                                          onTap: () async {
                                            try {
                                              await _initializeControllerFuture;

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

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

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

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

  final String outletName;
  final bool isIn;

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

class _WidgetAbsentAndTimeState extends State<WidgetAbsentAndTime> {
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    Timer.periodic(const Duration(seconds: 1), (timer) {
      _timer = timer;
      setState(() {});
    });
  }

  @override
  void dispose() {
    super.dispose();

    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(
        horizontal: AppMargin.m20,
      ),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        color: Colors.white,
      ),
      padding: const EdgeInsets.all(20),
      height: 105,
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            (widget.isIn) ? "Absen Masuk" : "Absen Keluar",
            style: getRegularStyle(
              color: Colors.black,
              fontSize: FontSize.s16,
              fontFamily: FontConstants.poppins,
            ),
          ),
          Text(
            "${widget.outletName} - ${DateFormatCustom.getLocalTime(
              timeZoneActive: true,
            )}",
            style: getSemiBoldStyle(
              color: Colors.black,
              fontSize: FontSize.s24,
            ),
          ),
        ],
      ),
    );
  }
}
