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

// class CameraScreen extends StatefulWidget {
//   @override
//   _CameraScreenState createState() => _CameraScreenState();
// }

// class _CameraScreenState extends State<CameraScreen> {
//   late CameraController _controller;
//   Future<void>? _initializeControllerFuture;
//   List<CameraDescription> cameras = [];
//   late CameraDescription firstCamera;
//   bool _isCameraInitialized = false;
//   File? imageFile;

//   @override
//   void initState() {
//     super.initState();
//     _initializeCamera();
//   }

//   Future<void> _initializeCamera() async {
//     try {
//       cameras = await availableCameras();
//       if (cameras.isEmpty) {
//         throw CameraException('No cameras available', '');
//       }
//       firstCamera = cameras.first;

//       _controller = CameraController(
//         firstCamera,
//         ResolutionPreset.high,
//       );

//       _initializeControllerFuture = _controller.initialize();
//       await _initializeControllerFuture;

//       if (!mounted) return;

//       setState(() {
//         _isCameraInitialized = true;
//       });

//       // Uncomment this line if you want to take a picture automatically after 2 seconds
//       Future.delayed(const Duration(seconds: 2), _takePictureAutomatically);
//     } catch (e) {
//       print('Error initializing camera: $e');
//       // Handle initialization error
//     }
//   }

//   Future<void> _takePictureAutomatically() async {
//     if (_controller.value.isInitialized) {
//       try {
//         XFile picture = await _controller.takePicture();
//         imageFile = File(picture.path);
//         print(imageFile!.path);
//         Navigator.pop(context, imageFile);
//       } catch (e) {
//         print('Error taking picture: $e');
//         // Handle error taking picture
//       }
//     }
//   }

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

//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       body: FutureBuilder<void>(
//         future: _initializeControllerFuture,
//         builder: (context, snapshot) {
//           if (snapshot.connectionState == ConnectionState.done &&
//               _isCameraInitialized) {
//             return CameraPreview(_controller);
//           } else {
//             return Center(child: CircularProgressIndicator());
//           }
//         },
//       ),
//     );
//   }
// }


import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

class CameraScreen extends StatefulWidget {

  @override
  _CameraScreenState createState() => _CameraScreenState();
}

class _CameraScreenState extends State<CameraScreen> {
  late CameraController _controller;
  Future<void>? _initializeControllerFuture;
  List<CameraDescription> cameras = [];
  late CameraDescription firstCamera;
  bool _isCameraInitialized = false;
  File? imageFile;
  
  @override
  void initState() {
    super.initState();
    _initializeCamera();
  }

  Future<void> _initializeCamera() async {
    try {
      cameras = await availableCameras();
      if (cameras.isEmpty) {
        throw CameraException('No cameras available', '');
      }
      firstCamera = cameras.first;
      _controller = CameraController(
        firstCamera,
        ResolutionPreset.veryHigh,
      );
      _initializeControllerFuture = _controller.initialize();
      await _initializeControllerFuture;
      if (mounted) {
        setState(() {
          _isCameraInitialized = true;
        });
      }
      Future.delayed(const Duration(seconds: 2), _takePicture);
    } catch (e) {
      if (kDebugMode) {
        print('Error initializing camera: $e');
      }
    }
  }

  void _takePicture() async {
    if (_controller.value.isInitialized) {
      try {
        XFile picture = await _controller.takePicture();
        imageFile = File(picture.path);
        Navigator.pop(context, imageFile);
      } catch (e) {
        if (kDebugMode) {
          print('Error taking picture: $e');
        }
      }
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          _isCameraInitialized
              ? GestureDetector(
                  onTap: () {
                    _takePicture();
                  },
                  child: SizedBox(
                    width: double.infinity,
                    height: double.infinity,
                    child: AspectRatio(
                      aspectRatio: _controller.value.aspectRatio,
                      child: CameraPreview(_controller),
                    ),
                  ),
                )
              : const Center(child: CircularProgressIndicator()),
        ],
      ),
    );
  }

  // @override
  // Widget build(BuildContext context) {
  //   return Scaffold(
  //     body: Stack(
  //       children: <Widget>[
  //         _isCameraInitialized
  //             ? GestureDetector(
  //                 onTap: () {
  //                   _takePicture();
  //                 },
  //                 child: OverflowBox(
  //                   maxWidth: double.infinity,
  //                   maxHeight: double.infinity,
  //                   child: AspectRatio(
  //                     aspectRatio: _controller.value.aspectRatio,
  //                     child: CameraPreview(_controller),
  //                   ),
  //                 ),
  //               )
  //             : Center(child: CircularProgressIndicator()),
  //       ],
  //     ),
  //   );
  // }

}
