import 'dart:async';
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

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

class FrontCameraCapture extends StatefulWidget {
  const FrontCameraCapture({Key? key}) : super(key: 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,
      );

      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 Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
      ),
      body: SafeArea(
        child: isLoading
            ? Center(child: CircularProgressIndicator())
            : Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Container(
              height: size.height * 0.8,
              child: cam_controller.value.isInitialized
                  ? CameraPreview(cam_controller)
                  : Center(child: Text("Camera not ready")),
            ),
            Container(
              height: size.height * 0.1,
              padding: EdgeInsets.all(10),
              child: Center(
                child: TextButton(
                  style: ButtonStyle(
                    backgroundColor: MaterialStatePropertyAll(Colors.white70),
                    overlayColor: MaterialStatePropertyAll(Colors.white70),
                  ),
                  onPressed: () async {
                    if (!cam_controller.value.isInitialized) return;
                    final image = await cam_controller.takePicture();
                    _image = File(image.path);
                    Navigator.pop(context, _image);
                  },
                  child: Icon(
                    CupertinoIcons.camera_circle_fill,
                    size: 50,
                    color: Colors.black,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
