import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Template/Camera/Bloc/CameraBloc.dart';
import 'package:absenkuv3/UI/Template/Camera/Model/CameraModel.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

// ignore: must_be_immutable
class CameraApp extends StatefulWidget {
  bool changeCamera;
  bool absensi;
  String defaultCamera;
  String? title;
  CameraApp(this.title, this.absensi,
      {this.changeCamera = false, this.defaultCamera = 'front'});
  @override
  _CameraAppState createState() => _CameraAppState();
}

class _CameraAppState extends State<CameraApp> {
  @override
  void initState() {
    super.initState();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    BlocProvider.of<CameraBloc>(context)
        .add(InitializeCamera(widget.defaultCamera, widget.absensi));
  }

  @override
  dispose() {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeRight,
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    debugPrint("DISPOSE");
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        flexibleSpace: Image(
          image: AssetImage(ValueImage.headerBiruDashboard),
          fit: BoxFit.cover,
        ),
        backgroundColor: Colors.black,
        title: Text(
          widget.title!,
          style: TextStyle(fontSize: CustomStyle.fontSizeTitle),
        ),
      ),
      body: BlocConsumer<CameraBloc, CameraState>(
        listener: (BuildContext context, CameraState state) {
          if (state is TakePictureSuccess)
            Navigator.pop(
              context,
              CameraModel(base64Encode(File(state.file.path).readAsBytesSync()),
                  state.file.path,
                  cameraId: state.cameraId),
            );
        },
        builder: (BuildContext context, CameraState state) {
          return Container(
            color: Colors.black,
            height: MediaQuery.of(context).size.height,
            child: Stack(
              children: [
                // cameraWidget(context, state.controller),
                state is InitializeCameraSuccess
                    ? Center(
                        child: Transform.scale(
                          scale: 1.0,
                          child: Container(
                            width: width,
                            height: width * state.controller!.value.aspectRatio,
                            child: Stack(
                              fit: StackFit.expand,
                              children: <Widget>[
                                CameraPreview(state.controller!),
                              ],
                            ),
                          ),
                        ),
                      )
                    : Container(
                        height: double.infinity,
                        width: double.infinity,
                        color: Colors.black,
                      ),
                Align(
                  alignment: Alignment.bottomCenter,
                  child: Container(
                    padding: EdgeInsets.only(bottom: 30),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      mainAxisSize: MainAxisSize.max,
                      children: [
                        Container(
                          width: 60,
                          height: 10,
                        ),
                        Container(
                          width: 66,
                          height: 66,
                          // padding: EdgeInsets.all(3),
                          decoration: BoxDecoration(boxShadow: [
                            BoxShadow(
                              color: Colors.grey.withOpacity(0.4),
                              spreadRadius: 2,
                              blurRadius: 5,
                              offset:
                                  Offset(0, 1), // changes position of shadow
                            ),
                          ], color: Colors.white, shape: BoxShape.circle),
                          child: state is InitializeCameraProgress
                              ? ClipRRect(
                                  borderRadius: BorderRadius.circular(120.0),
                                  child: Container(
                                    // padding: EdgeInsets.all(8),
                                    child: Image.asset(ValueImage.cameraIcon),
                                    // CircularProgressIndicator(
                                    //   valueColor:
                                    //       new AlwaysStoppedAnimation<Color>(
                                    //           Colors.grey),
                                    // ),
                                  ),
                                )
                              : GestureDetector(
                                  onTap: () =>
                                      BlocProvider.of<CameraBloc>(context)
                                          .add(TakePicture()),
                                  child: Image.asset(ValueImage.cameraIcon),
                                  // child: new Icon(
                                  //   Icons.camera_alt,
                                  //   color: CustomStyle.fontColorBlack,
                                  //   size: 46,
                                  // )
                                ),
                        ),
                        Container(
                          width: 40,
                          height: 40,
                          margin: EdgeInsets.only(left: 12),
                          child: widget.changeCamera
                              ? Container(
                                  // padding: EdgeInsets.all(10),
                                  decoration: BoxDecoration(
                                      boxShadow: [
                                        BoxShadow(
                                          color: Colors.grey.withOpacity(0.4),
                                          spreadRadius: 2,
                                          blurRadius: 5,
                                          offset: Offset(0,
                                              1), // changes position of shadow
                                        ),
                                      ],
                                      color: Colors.white,
                                      shape: BoxShape.circle),
                                  child: state is InitializeCameraProgress
                                      ? ClipRRect(
                                          borderRadius:
                                              BorderRadius.circular(120.0),
                                          child: Container(
                                            padding: EdgeInsets.all(8),
                                            child: CircularProgressIndicator(
                                              strokeWidth: 3,
                                              valueColor:
                                                  new AlwaysStoppedAnimation<
                                                      Color>(Colors.grey),
                                            ),
                                          ),
                                        )
                                      : GestureDetector(
                                          onTap: () =>
                                              BlocProvider.of<CameraBloc>(
                                                      context)
                                                  .add(ChangeCamera()),
                                          child: Image.asset(
                                              ValueImage.flipCameraIcon),
                                          // child: new Icon(
                                          //   Icons.rotate_left_sharp,
                                          //   color: CustomStyle.fontColorBlack,
                                          //   size: 30,
                                          // )
                                        ),
                                )
                              : Container(),
                        ),
                      ],
                    ),
                  ),
                )
              ],
            ),
          );
        },
      ),
    );
  }

  Widget cameraWidget(context, _cameraController) {
    var camera = _cameraController.value;
    // fetch screen size
    final size = MediaQuery.of(context).size;

    // calculate scale depending on screen and camera ratios
    // this is actually size.aspectRatio / (1 / camera.aspectRatio)
    // because camera preview size is received as landscape
    // but we're calculating for portrait orientation
    var scale = size.aspectRatio * camera.aspectRatio;

    // to prevent scaling down, invert the value
    if (scale < 1) scale = 1 / scale;

    return Transform.scale(
      scale: scale,
      child: Center(
        child: CameraPreview(_cameraController),
      ),
    );
  }
}
