import 'dart:async';
import 'dart:io';
import 'dart:math' as math;
import 'package:camera/camera.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:permission_handler/permission_handler.dart';

import '../Utils/commonServices.dart';

class FrontCameraCapture extends StatefulWidget {
  const FrontCameraCapture({super.key});

  @override
  State<FrontCameraCapture> createState() => _CheckOutScreenState();
}

class _CheckOutScreenState extends State<FrontCameraCapture> {
  late List<CameraDescription> _cameras;
  late CameraController cam_controller;

  File? _image;
  var image_picked = 0;
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    initCameraSetup();
  }

  Future<void> initCameraSetup() async {
    await requestCameraPermission();
    await _getavailableCameras();
  }

  Future<void> requestCameraPermission() async {
    var status = await Permission.camera.status;
    if (!status.isGranted) {
      status = await Permission.camera.request();
    }

    if (!status.isGranted) {
      toast(context, "Camera permission denied");
      Navigator.pop(context);
    }
  }

  Future<void> _getavailableCameras() async {
    try {
      _cameras = await availableCameras();
      //
      final frontCamera = _cameras.firstWhere(
        (camera) => camera.lensDirection == CameraLensDirection.front,
      );
      // final frontCamera = CameraLensDirection.front;
      cam_controller = CameraController(frontCamera, ResolutionPreset.max);

      await cam_controller.initialize();

      if (!mounted) return;
      setState(() {
        isLoading = false;
      });
    } catch (e) {
      toast(context, "Failed to initialize camera");
      Navigator.pop(context);
    }
  }

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

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;

    return SafeArea(
      top: false,
      bottom: Platform.isIOS ? false : true,
      child: Scaffold(
        // appBar: AppBar(automaticallyImplyLeading: false),
        body:
            isLoading
                ? Center(child: CircularProgressIndicator())
                : Row(
                  children: [
                    Expanded(
                      child: SizedBox(
                        height: double.infinity,
                        child:
                            cam_controller.value.isInitialized
                                ? Transform(
                                  alignment: Alignment.center,
                                  transform: Matrix4.rotationY(math.pi),
                                  child: CameraPreview(
                                    cam_controller,
                                    child: Align(
                                      alignment: Alignment.bottomCenter,
                                      child: GestureDetector(
                                        onTap: () async {
                                          if (!cam_controller
                                              .value
                                              .isInitialized) {
                                            return;
                                          }
                                          final image =
                                              await cam_controller
                                                  .takePicture();
                                          _image = File(image.path);
                                          Navigator.pop(context, _image);
                                        },
                                        child: Container(
                                          height: 100,
                                          width: double.infinity,
                                          padding: EdgeInsets.all(10),
                                          decoration: BoxDecoration(
                                            color: Colors.black26,
                                          ),
                                          child: Center(
                                            child: SvgPicture.asset(
                                              "assets/svg/check_in_cam.svg",
                                              width: 50,
                                              height: 50,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                )
                                : Center(child: Text("Camera not ready")),
                      ),
                    ),
                  ],
                ),
      ),
    );
  }
}
