import 'dart:io';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Template/Camera/Model/CameraModel.dart';
import 'package:absenkuv3/UI/Template/MultiImagePicker/Bloc/MultiImagePickerBloc.dart';
import 'package:absenkuv3/UI/Template/MultiImagePicker/Model/MultiImagePickerModel.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class TemplateMultiImageSOS extends StatefulWidget {
  var borderColor;
  final double bottomMargin;
  final bool multiImage;
  final bool fromCamera;
  final String defaultCamera;
  final String? pluginCamera;
  final int maxUpload;
  List<String?>? initialData;
  TemplateMultiImageSOS(
      {this.initialData,
      this.borderColor,
      this.bottomMargin = 12,
      this.multiImage = true,
      this.fromCamera = false,
      this.defaultCamera = 'front',
      this.pluginCamera = '1',
      this.maxUpload = 3});
  @override
  _TemplateMultiImageSOSState createState() =>
      _TemplateMultiImageSOSState();
}

class _TemplateMultiImageSOSState
    extends State<TemplateMultiImageSOS> {
  CameraModel? cameraModel;

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: PengaturanBahasa().getDataBahasa(),
      builder: (BuildContext context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          String language = snapshot.data.toString();
          return Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                  margin: EdgeInsets.only(left: 3,bottom: 10),
                  child: Text(
                    language == 'id' ? "Upload File" : "Upload File",
                    style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
                  )),
              Container(
                width: MediaQuery.of(context).size.width,
                child: Stack(
                  children: [
                    BlocBuilder<MultiImagePickerBloc, MultiImagePickerState>(
                        builder: (BuildContext context,
                            MultiImagePickerState state) {
                      List<Widget> children = [];
                      if (state is MultiImageSuccessState) {
                        children.addAll(
                            state.listData.map((image) => ImageCard(image)));
                        children.add(state.listData != null &&
                                state.listData.isNotEmpty &&
                                state.listData.length < widget.maxUpload
                            ? GestureDetector(
                                onTap: () async {
                                  await popupPilihSumberFoto(context, language);
                                },
                                child: Image.asset(ValueImage.plus),
                              )
                            : SizedBox.shrink());
                        return GridView.count(
                            shrinkWrap: true,
                            crossAxisCount: 4,
                            crossAxisSpacing: 8,
                            mainAxisSpacing: 8,
                            children: children);
                      } else if (widget.initialData != null) {
                        children.addAll(widget.initialData!
                            .map((item) => InitalImageCard(item!))
                            .toList());
                        children.add(IconButton(
                            onPressed: () async {
                              await popupPilihSumberFoto(context, language);
                            },
                            icon: Icon(Icons.add_box,
                                color: Colors.grey, size: 70)));
                        return GridView.count(
                            shrinkWrap: true,
                            crossAxisCount: 4,
                            crossAxisSpacing: 8,
                            mainAxisSpacing: 8,
                            children: children);
                      } else {
                        return SizedBox(
                          height: 70,
                        );
                      }
                    }),
                    widget.initialData == null
                        ? Positioned.fill(child: BlocBuilder<
                                MultiImagePickerBloc, MultiImagePickerState>(
                            builder: (BuildContext context,
                                MultiImagePickerState state) {
                            if (state is MultiImageSuccessState) {
                              if (state.listData == null ||
                                  state.listData.isEmpty) {
                                return Align(
                                    alignment: Alignment.centerLeft,
                                    child: GestureDetector(
                                      onTap: () async {
                                        await popupPilihSumberFoto(
                                            context, language);
                                      },
                                      child: Container(
                                          child: Row(
                                        children: [
                                          Image.asset(ValueImage.plus,width: 70,height: 70,),
                                          Expanded(
                                            child: Container(
                                              margin: EdgeInsets.only(left: 10),
                                              child: Text(
                                                language == 'id'
                                                    ? "Tambah file untuk mendukung sos dalam format JPG atau PNG, dan makisimal 2 file."
                                                    : "Add files to support the sos in JPG or PNG format, with a maximum of 2 files. ",
                                                style: TextStyle(
                                                    color: Colors.grey),
                                              ),
                                            ),
                                          )
                                        ],
                                      )),
                                    ));
                              }
                              return Container();
                            }
                            return Align(
                                alignment: Alignment.centerLeft,
                                child: GestureDetector(
                                  onTap: () async {
                                    await popupPilihSumberFoto(
                                        context, language);
                                  },
                                  child: Container(
                                      child: Row(
                                    children: [
                                      Image.asset(ValueImage.plus),
                                      Expanded(
                                        child: Container(
                                          margin: EdgeInsets.only(left: 10),
                                          child: Text(
                                            language == 'id'
                                                ? "Tambah file untuk mendukung sos dalam format JPG atau PNG, dan makisimal 2 file."
                                                    : "Add files to support the sos in JPG or PNG format, with a maximum of 2 files.",
                                            style:
                                                TextStyle(color: Colors.grey),
                                          ),
                                        ),
                                      )
                                    ],
                                  )),
                                ));
                          }))
                        : Container()
                  ],
                ),
              ),
            ],
          );
        } else {
          return Container();
        }
      },
    );
  }

  Future<void> _dialogBuilder(
      BuildContext context, MultiImagePickerModel image) {
    return showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(32.0))),
          content: Container(
            child: InteractiveViewer(
                boundaryMargin: EdgeInsets.all(20.0),
                minScale: 0.5,
                maxScale: 2.0,
                child: Image.file(File(image.path))),
          ),
          actions: <Widget>[
            TextButton(
              style: TextButton.styleFrom(
                textStyle: Theme.of(context).textTheme.labelLarge,
              ),
              child: const Text('Tutup'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  Future<void> _initialdialogBuilder(BuildContext context, String image) {
    return showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(32.0))),
          content: Container(
            child: InteractiveViewer(
                boundaryMargin: EdgeInsets.all(20.0),
                minScale: 0.5,
                maxScale: 2.0,
                child: Image.network(image)),
          ),
          actions: <Widget>[
            TextButton(
              style: TextButton.styleFrom(
                textStyle: Theme.of(context).textTheme.labelLarge,
              ),
              child: const Text('Tutup'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  Widget ImageCard(MultiImagePickerModel image) {
    return Container(
      child: Stack(
        children: [
          GestureDetector(
            onTap: () {
              _dialogBuilder(context, image);
            },
            child: 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),
                  ),
                ),
              ),
            ),
          ),
          Positioned(
            right: 0,
            top: 0,
            child: GestureDetector(
              onTap: () {
                BlocProvider.of<MultiImagePickerBloc>(context)
                    .add(DeleteImage(image));
                setState(() {
                  widget.initialData = null;
                });
              },
              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,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget InitalImageCard(String image) {
    return Container(
      child: Stack(
        children: [
          GestureDetector(
            onTap: () {
              _initialdialogBuilder(context, image);
            },
            child: 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.network(image),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  popupPilihSumberFoto(context, String language) {
    showModalBottomSheet(
      showDragHandle: true,
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30.0),
          topRight: Radius.circular(30.0),
        ),
      ),
      backgroundColor: Colors.white,
      context: context,
      builder: (ctx) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
                margin: EdgeInsets.only(left: 20),
                child: Text(
                  language == 'id' ? "Upload Foto" : "Upload Photo",
                  style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold),
                )),
            Divider(),
            Padding(
              padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
              child: Column(
                children: [
                  GestureDetector(
                    onTap: () async {
                      final fromCamera = true;
                      final event = widget.multiImage
                          ? PickImage(context, false,
                              fromCamera: fromCamera,
                              defaultCamera: widget.defaultCamera,
                              pluginCamera: widget.pluginCamera)
                          : PickImageSingle(context, false,
                              fromCamera: fromCamera,
                              defaultCamera: widget.defaultCamera,
                              pluginCamera: widget.pluginCamera);
                      BlocProvider.of<MultiImagePickerBloc>(context).add(event);
                      Navigator.pop(context);
                    },
                    child: Container(
                      padding: EdgeInsets.all(16),
                      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(
                              language == 'id'
                                  ? "Ambil dari Kamera"
                                  : "Take from camera",
                              style: TextStyle(fontSize: 18),
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(height: 24),
                  GestureDetector(
                    onTap: () async {
                      final fromCamera = false;
                      final event = widget.multiImage
                          ? PickImage(context, false,
                              fromCamera: fromCamera,
                              defaultCamera: widget.defaultCamera,
                              pluginCamera: widget.pluginCamera)
                          : PickImageSingle(context, false,
                              fromCamera: fromCamera,
                              defaultCamera: widget.defaultCamera,
                              pluginCamera: widget.pluginCamera);
                      BlocProvider.of<MultiImagePickerBloc>(context).add(event);
                      Navigator.pop(context);
                    },
                    child: Container(
                      padding: EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12),
                        color: Colors.grey[200],
                      ),
                      child: Row(
                        children: [
                          Icon(Icons.image, size: 30),
                          SizedBox(width: 16),
                          Expanded(
                            child: Text(
                              language == 'id'
                                  ? "Ambil dari Galeri"
                                  : "Select from Gallery",
                              style: TextStyle(fontSize: 18),
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        );
      },
    );
  }
}
