import 'dart:convert';
import 'dart:io';

import 'package:absenkuv3/Repository/Model/mLogin.dart';
import 'package:absenkuv3/Repository/sharedPreference.dart';
import 'package:absenkuv3/UI/Template/Camera/Bloc/CameraBloc.dart';
import 'package:absenkuv3/UI/Template/Camera/Model/CameraModel.dart';
import 'package:absenkuv3/UI/Template/Camera/UI/HalamanCamera.dart';
import 'package:absenkuv3/UI/Template/CameraX/Model/CameraXRespon.dart';
import 'package:absenkuv3/UI/Template/MultiImagePicker/Bloc/MultiImagePicker3Bloc.dart';
import 'package:absenkuv3/UI/Template/MultiImagePicker/Model/MultiImagePickerModel.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

class TemplateImagePicker3 extends StatefulWidget {
  final int totalUpload;
  final String title;
  final bool fromCamera;
  final bool fromGaleri;
  TemplateImagePicker3({this.totalUpload=1, this.title = "Ambil Foto", this.fromCamera = true, this.fromGaleri = true}) : super();

  @override
  State<TemplateImagePicker3> createState() => _TemplateImagePicker3();
}

class _TemplateImagePicker3 extends State<TemplateImagePicker3> {
  CameraModel? cameraModel;

  static const MethodChannel methodChannel = MethodChannel('absenku/camerax');
  static const EventChannel eventChannel =
      EventChannel('absenku/camerax/report');

  String _reportStatus = ' {"foto":"","matrix":""}';
  String? foto = "";
  String? matrix = "";
  var registrasi = false;
  String? kamera2;
  
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    BlocProvider.of<MultiImagePicker3Bloc>(context).add(clearImagePicker());
  }

  @override
    Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      child: Stack(
        children: [
          BlocBuilder<MultiImagePicker3Bloc, ImagePickerState>(
            builder: (BuildContext context, ImagePickerState state) {
              List<Widget> children = [];
              if (state is gettImageSuccessState) {
                children.addAll(
                    state.listImage!.map((image) => ImageCard(image)));
              }
              children.add(state.listImage != null &&
                      state.listImage!.isNotEmpty
                  ? state.listImage!.length < widget.totalUpload ? 
                  IconButton(
                      onPressed: () async {
                        if (state.listImage!.isEmpty) {
                          await popUpModalBottom(context, widget.title, widget.fromCamera, widget.fromGaleri);
                        }
                        else {
                          await popUpModalBottom(context, widget.title, widget.fromCamera, widget.fromGaleri);
                        }
                      },
                      icon: Icon(Icons.add_box, color: CustomStyle.color1, size: 51)):Container()
                  : SizedBox.shrink());

              return GridView.count(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  crossAxisCount: 4,
                  crossAxisSpacing: 8,
                  mainAxisSpacing: 8,
                  children: children);
            },
          ),
          Positioned.fill(child:
              BlocBuilder<MultiImagePicker3Bloc, ImagePickerState>(
                  builder: (BuildContext context, ImagePickerState state) {
            if (state.listImage == null || state.listImage!.isEmpty) {
              return Align(
                  alignment: Alignment.centerLeft,
                  child: GestureDetector(
                    onTap: () async {
                      await popUpModalBottom(context, widget.title, widget.fromCamera, widget.fromGaleri);
                    },
                    child: Container(
                      child:
                          Icon(Icons.add_box, color: CustomStyle.color1, size: 51),
                    ),
                  ));
            }
            return Container();
          }
          )
          )
        ],
      ),
    );
  }

  Widget ImageCard(MultiImagePickerModel image) {
    return Container(
      child: Stack(
        children: [
          Container(
            margin: EdgeInsets.all(5),
            child: DottedBorder(
              color: Colors.grey,
              strokeWidth: 1,
              radius: Radius.circular(5),
              borderType: BorderType.RRect,
              dashPattern: [8, 2],
              child: Container(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                padding: EdgeInsets.all(10),
                child: Image.file(
                  File(image.path),
                  // fit: BoxFit.cover,
                ),
              ),
            ),
          ),
          Positioned(
            right: 0,
            top: 0,
            child: GestureDetector(
              onTap: () => BlocProvider.of<MultiImagePicker3Bloc>(context)
                  .add(deleteImagePicker(image)),
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.red,
                  borderRadius: BorderRadius.circular(50),
                  border: Border.all(color: Colors.red, width: 2),
                ),
                child: Icon(
                  Icons.close,
                  color: Colors.white,
                  size: 18,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  popUpModalBottom(context, String title, bool fromCamera, bool fromGaleri) {
    showModalBottomSheet(
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30.0),
          topRight: Radius.circular(30.0),
        ),
      ),
      backgroundColor: Colors.white,
      context: context,
      builder: (BuildContext ctx) {
        return Padding(
          padding: EdgeInsets.all(24), // Increased padding
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisSize: MainAxisSize.min,
            children: [
              !fromCamera ? Container() :
              GestureDetector(
                onTap: () async {
                  LoginRespon login = await sharedPreferences().getUserData();
                  String? kamera = login.dataLogin!.kamera;
                  if (kamera == '2') {
                    if (Platform.isIOS) {
                      kamera = '1';
                    }
                  }
                  var status = await Permission.camera.status;
                  if (status.isDenied || status.isPermanentlyDenied) {
                    if (status.isPermanentlyDenied) {
                      // jenisPeringatan = "PermissionGPS";
                      // popUpPeringatan("Anda belum menyetujui penggunaan Camera", context);
                    } else {
                      await Permission.camera.request();
                    }
                  } else {
                    // lifeCycleStateInit = false;
                    if (kamera == '1')
                      cameraModel = await Navigator.push<CameraModel>(
                          context,
                          MaterialPageRoute(
                              builder: (_) => BlocProvider(
                                    create: (BuildContext context) =>
                                        CameraBloc(InitializeCameraProgress()),
                                    child: CameraApp(
                                      title,
                                      false,
                                      changeCamera: true,
                                      defaultCamera: 'back',
                                    ),
                                  )));
                    else if (kamera == '2') {
                      cameraModel = await routeCameraX(kamera!);
                    } else {
                      XFile? pickedFile = await ImagePicker().pickImage(
                          source: ImageSource.camera,
                          imageQuality: 75,
                          maxWidth: 400);
                      if (pickedFile != null)
                        cameraModel = CameraModel(
                            base64Encode(
                                File(pickedFile.path).readAsBytesSync()),
                            pickedFile.path);
                    }
                    print(cameraModel);
                    BlocProvider.of<MultiImagePicker3Bloc>(context).add(
                        addImageEvent(
                            context,
                            MultiImagePickerModel(
                                cameraModel!.base64, cameraModel!.path)));
                    Navigator.pop(context);
                  }
                },
                child: Container(
                  padding: EdgeInsets.all(16), // Increased padding
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12),
                    color: Colors.grey[200],
                  ),
                  child: Row(
                    children: [
                      Icon(Icons.camera_alt, size: 30),
                      SizedBox(width: 16),
                      Expanded(
                        child: Text(
                          "Ambil dari Kamera",
                          style: TextStyle(fontSize: 18), // Increased text size
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              // Container 2: Pick with File
              !fromGaleri ? Container() :
              Column(
                children: [
                  SizedBox(height: 24), // Increased spacing
                  GestureDetector(
                    onTap: () async {
                      XFile? pickedFile = await ImagePicker().pickImage(
                          source: ImageSource.gallery,
                          imageQuality: 75,
                          maxWidth: 400);
                      if (pickedFile != null)
                        cameraModel = CameraModel(
                            base64Encode(File(pickedFile.path).readAsBytesSync()),
                            pickedFile.path);
                            print(cameraModel);
                      BlocProvider.of<MultiImagePicker3Bloc>(context).add(addImageEvent(
                          context,
                          MultiImagePickerModel(
                              cameraModel!.base64, cameraModel!.path)));
                      Navigator.pop(context);
                    },
                    child: Container(
                      padding: EdgeInsets.all(16), // Increased padding
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12),
                        color: Colors.grey[200],
                      ),
                      child: Row(
                        children: [
                          Icon(Icons.image, size: 30),
                          SizedBox(width: 16),
                          Expanded(
                            child: Text(
                              "Ambil dari Galeri",
                              style: TextStyle(fontSize: 18), // Increased text size
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  popupPilihSumberFoto(context) {
    showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            shape: RoundedRectangleBorder(
                borderRadius:
                    BorderRadius.all(Radius.circular(CustomStyle.boxRadius))),
            content: SingleChildScrollView(
              reverse: true,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  //Gallery
                  GestureDetector(
                    onTap: () async {
                      XFile? pickedFile = await ImagePicker().pickImage(
                          source: ImageSource.gallery,
                          imageQuality: 75,
                          maxWidth: 400);
                      print("print pick ${pickedFile!.path}");
                      if (pickedFile != null)
                        cameraModel = CameraModel(
                            base64Encode(
                                File(pickedFile.path).readAsBytesSync()),
                            pickedFile.path);
                      BlocProvider.of<MultiImagePicker3Bloc>(context).add(
                          addImageEvent(
                              context,
                              MultiImagePickerModel(
                                  cameraModel!.base64, cameraModel!.path)));
                      Navigator.pop(context);
                    },
                    child: Container(
                      child: Column(
                        children: [
                          Icon(
                            Icons.photo,
                            color: Colors.redAccent,
                            size: 40,
                          ),
                          Text("Gallery")
                        ],
                      ),
                    ),
                  ),
                  //Kamara
                  GestureDetector(
                    onTap: () async {
                      LoginRespon login =
                          await sharedPreferences().getUserData();
                      String? kamera = login.dataLogin!.kamera;
                      if (kamera == '2') {
                        if (Platform.isIOS) {
                          kamera = '1';
                        }
                      }
                      var status = await Permission.camera.status;
                      if (status.isDenied || status.isPermanentlyDenied) {
                        if (status.isPermanentlyDenied) {
                          // jenisPeringatan = "PermissionGPS";
                          // popUpPeringatan("Anda belum menyetujui penggunaan Camera", context);
                        } else {
                          await Permission.camera.request();
                        }
                      } else {
                        // lifeCycleStateInit = false;
                        print('testing mlebu');
                        if (kamera == '1')
                          cameraModel = await Navigator.push<CameraModel>(
                              context,
                              MaterialPageRoute(
                                  builder: (_) => BlocProvider(
                                        create: (BuildContext context) =>
                                            CameraBloc(
                                                InitializeCameraProgress()),
                                        child: CameraApp(
                                          "Foto",
                                          false,
                                          changeCamera: true,
                                          defaultCamera: 'back',
                                        ),
                                      )));
                        else if (kamera == '2') {
                          cameraModel = await routeCameraX(kamera!);
                        } else {
                          XFile? pickedFile = await ImagePicker().pickImage(
                              source: ImageSource.camera,
                              imageQuality: 75,
                              maxWidth: 400);
                          if (pickedFile != null)
                            cameraModel = CameraModel(
                                base64Encode(
                                    File(pickedFile.path).readAsBytesSync()),
                                pickedFile.path);
                        }

                        BlocProvider.of<MultiImagePicker3Bloc>(context).add(
                            addImageEvent(
                                context,
                                MultiImagePickerModel(
                                    cameraModel!.base64, cameraModel!.path)));
                        Navigator.pop(context);
                      }
                    },
                    child: Container(
                      child: Column(
                        children: [
                          Icon(
                            Icons.camera_alt,
                            color: Colors.redAccent,
                            size: 40,
                          ),
                          Text("Camera")
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        });
  }

  routeCameraX(String kamera) {
    _startCameraXActivity(kamera, true);
  }

  Future<void> _startCameraXActivity(String kamera, bool kameraBelakang) async {
    setState(() {
      this.kamera2 = kamera;
      // registrasi = register;
    });
    try {
      eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
      await methodChannel.invokeMethod('startCameraXActivity', {
        "kameraBelakang": kameraBelakang,
      });
    } on PlatformException catch (e) {
      debugPrint("Failed to Invoke: '${e.message}'.");
    }
  }

  void _onEvent(Object? event) {
    setState(() {
      _reportStatus = event.toString();
      CameraXRespon cameraXRespon = cameraXResponFromJson(_reportStatus);

      foto = cameraXRespon.foto;
      matrix = cameraXRespon.matrix;

      cameraModel =
          CameraModel(base64Encode(File(foto!).readAsBytesSync()), foto!);
      BlocProvider.of<MultiImagePicker3Bloc>(context).add(addImageEvent(
          context,
          MultiImagePickerModel(
            cameraModel!.base64,
            cameraModel!.path,
          )));
      Navigator.pop(context);
      // openDialog(context, rotate: false);
    });
  }

  void _onError(Object error) {
    setState(() {
      _reportStatus = 'Camera status: ${error.toString()}';
    });
  }
}
