import 'package:camera/camera.dart';
import 'package:cims_apps/application/assets/path_assets.dart';
import 'package:cims_apps/application/component/image/image_view.dart';
import 'package:cims_apps/application/component/take_picture_screen/DisplayPictureScreen.dart';
import 'package:cims_apps/core/route/route.dart';
import 'package:cims_apps/core/utils/size_config.dart';
import 'package:flutter/material.dart';

class TakePictureScreen extends StatefulWidget {
  const TakePictureScreen({
    super.key,
    required this.camera,
    required this.takeContent,
  });

  final CameraDescription camera;
  final String takeContent;

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

class TakePictureScreenState extends State<TakePictureScreen> {
  late CameraController _controller;
  late Future<void> _initializeControllerFuture;
  bool isFlash = false;
  late String _takeContent;

  Future<void> changeFlash() async {
    await _controller.setFlashMode(FlashMode.auto);
    setState(() {
      isFlash = !isFlash;
    });
  }

  @override
  void initState() {
    super.initState();
    _controller = CameraController(
      widget.camera,
      ResolutionPreset.medium,
      enableAudio: false,
    );
    // Next, initialize the controller. This returns a Future.
    _initializeControllerFuture = _controller.initialize();
    _takeContent = widget.takeContent;
  }

  @override
  void dispose() {
    // Dispose of the controller when the widget is disposed.
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Fill this out in the next steps.
    return Scaffold(
      appBar: AppBar(
        title: const Text('Registration'),
        actions: [
          IconButton(
              onPressed: () {
                changeFlash();
              },
              icon: Icon(isFlash ? Icons.flash_on : Icons.flash_off))
        ],
      ),
      body: FutureBuilder<void>(
        future: _initializeControllerFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            // If the Future is complete, display the preview.
            return Stack(
              children: [
                SizedBox(
                    width: SizeConfig.width,
                    height: SizeConfig.height,
                    child: CameraPreview(_controller)),
                Container(
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Colors.transparent,
                        Colors.black.withOpacity(0.5),
                      ],
                    ),
                  ),
                  child: ImageView(
                    image: _takeContent == 'ktp'
                        ? PathAssets.imgBgKtp
                        : PathAssets.imgBgSelfie,
                    width: SizeConfig.width,
                    height: SizeConfig.height,
                  ),
                ),
                Align(
                  alignment: Alignment.bottomCenter,
                  child: IconButton(
                    onPressed: () async {
                      try {
                        // Ensure that the camera is initialized.
                        await _initializeControllerFuture;

                        // Attempt to take a picture and get the file `image`
                        // where it was saved.
                        final image = await _controller.takePicture();

                        if (!mounted) return;
                        routePush(context,
                            page: DisplayPictureScreen(
                              imagePath: image.path,
                              content: _takeContent,
                            ),
                            routeType: RouteType.pushReplace);
                      } catch (e) {
                        // If an error occurs, log the error to the console.
                        debugPrint(e.toString());
                      }
                    },
                    icon: Icon(
                      Icons.album_outlined,
                      color: Colors.white,
                      size: SizeConfig.width * .16,
                    ),
                  ),
                )
              ],
            );
          } else {
            return const Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}
