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

import 'package:absenkuv3/Repository/sharedPreference.dart';
import 'package:absenkuv3/UI/Template/MultiImagePicker/Bloc/MultiImagePickerBloc.dart';
import 'package:absenkuv3/UI/Template/MultiImagePicker/Model/MultiImagePickerModel.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:absenkuv3/UI/Template/templateButton.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

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

class _TemplateMultiImagePickerState extends State<TemplateMultiImagePicker> {

  Future getDataBahasa() async {
    String jsonString;
    String bahasa = await sharedPreferences().getBahasa();
    if(bahasa == 'id'){
      jsonString = await rootBundle.loadString('assets/id/template/template_multi_image_picker.json');
    }else{
      jsonString = await rootBundle.loadString('assets/en/template/template_multi_image_picker.json');
    }
    var data = json.decode(jsonString);
    return data;
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: getDataBahasa(),
        builder: (context, snapshot){
          return Container(
            margin: EdgeInsets.only(bottom: widget.bottomMargin),
            child: ConstrainedBox(constraints: BoxConstraints(
                minHeight: 180,
                minWidth: MediaQuery.of(context).size.width
            ),
              child: Container(
                padding: EdgeInsets.only(top: 16, bottom: 16),
                decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border.all(
                        width: 0.8,
                        color: widget.borderColor!=null?widget.borderColor:Colors.grey[600]!),
                    borderRadius:
                    new BorderRadius.all(Radius.circular(8))),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    BlocBuilder<MultiImagePickerBloc, MultiImagePickerState>(
                      builder: (BuildContext context, MultiImagePickerState state){
                        if(state is MultiImageSuccessState){
                          return Container(
                            margin: EdgeInsets.only(bottom: 18),
                            child: state.listData!=null&&state.listData.length>0?widget.multiImage?Wrap(
                              spacing: 6,
                              runSpacing: 4,
                              children: state.listData
                                  .map((item) => ImageCard(item))
                                  .toList(),
                            ):Stack(
                              children: [
                                Container(
                                  padding: EdgeInsets.all(6),
                                  child: Image.file(File(state.listData[0].path)),
                                ),
                                Align(
                                    alignment: Alignment.topRight,
                                    child: GestureDetector(
                                      onTap: () => BlocProvider.of<MultiImagePickerBloc>(context).add(DeleteImage(state.listData[0])),
                                      child: Container(
                                          margin: EdgeInsets.fromLTRB(0, 5, 5, 0),
                                          decoration: BoxDecoration(
                                            shape: BoxShape.circle,
                                            color: Colors.white,
                                          ),
                                          child: Icon(Icons.close)),
                                    ))
                              ],
                            ):widget.multiImage?Container() : TemplateButton(
                              onClick: ()=>BlocProvider.of<MultiImagePickerBloc>(context).add(widget.multiImage?PickImage(context, false, fromCamera: widget.fromCamera, defaultCamera: widget.defaultCamera, pluginCamera: widget.pluginCamera):PickImageSingle(context, false, fromCamera: widget.fromCamera, defaultCamera: widget.defaultCamera, pluginCamera: widget.pluginCamera)),
                              label: widget.fromCamera
                                      ? snapshot.data == null ? 'Take Photo' : snapshot.data['template_multi_image_picker']['ambil_foto']
                                      : snapshot.data == null ? 'Take Image' : snapshot.data['template_multi_image_picker']['ambil_gambar'], color: Colors.grey[100], borderColor: Colors.grey[500], radius: CustomStyle.boxRadius, contentColor: Colors.grey[500], paddingLeftRight: 8, heightButton: 32, paddingTopBottom: 0, icon: Icons.add,),
                          );
                        }
                        else if(widget.initialData!=null)return Container(
                            margin: EdgeInsets.only(bottom: 18),
                            child: widget.initialData!.length>1?Wrap(
                              spacing: 6,
                              runSpacing: 4,
                              children: widget.initialData!
                                  .map((item) => Image.network(item!))
                                  .toList(),
                            ):Container(
                                padding: EdgeInsets.all(6),
                                child: Stack(
                                  children: [
                                    Image.network(widget.initialData![0]!, errorBuilder: (c,obj,st){
                                      return Text(widget.initialData![0].toString());
                                    }),
                                    Align(
                                      alignment: Alignment.topRight,
                                      child: GestureDetector(
                                        onTap: () => BlocProvider.of<MultiImagePickerBloc>(context).add(DeleteImage(MultiImagePickerModel('',''))),
                                        child: Container(
                                            margin: EdgeInsets.fromLTRB(0, 5, 5, 0),
                                            decoration: BoxDecoration(
                                              shape: BoxShape.circle,
                                              color: Colors.white,
                                            ),
                                            child: Icon(Icons.close)),
                                      ),
                                    )
                                  ],
                                )));
                        else return widget.multiImage==true?Container():
                          TemplateButton(
                            onClick: ()=>BlocProvider.of<MultiImagePickerBloc>(context).add(widget.multiImage?PickImage(context, false, fromCamera: widget.fromCamera, defaultCamera: widget.defaultCamera, pluginCamera: widget.pluginCamera):PickImageSingle(context, false, fromCamera: widget.fromCamera, defaultCamera: widget.defaultCamera, pluginCamera: widget.pluginCamera)),
                            label: widget.fromCamera
                                ? snapshot.data == null ? 'Take Photo' : snapshot.data['template_multi_image_picker']['ambil_foto']
                                : snapshot.data == null ? 'Take Image' : snapshot.data['template_multi_image_picker']['ambil_gambar'], color: Colors.grey[100], borderColor: Colors.grey[500], radius: CustomStyle.boxRadius, contentColor: Colors.grey[500], paddingLeftRight: 8, heightButton: 32, paddingTopBottom: 0, icon: Icons.add,);
                      },
                    ),
                    widget.multiImage==false ? Container() :
                    TemplateButton(
                      onClick: ()=>BlocProvider.of<MultiImagePickerBloc>(context).add(widget.multiImage?PickImage(context, false, fromCamera: widget.fromCamera, defaultCamera: widget.defaultCamera, pluginCamera: widget.pluginCamera):PickImageSingle(context, false, fromCamera: widget.fromCamera, defaultCamera: widget.defaultCamera, pluginCamera: widget.pluginCamera)),
                      label: widget.fromCamera
                          ? snapshot.data == null ? 'Take Photo' : snapshot.data['template_multi_image_picker']['ambil_foto']
                          : snapshot.data == null ? 'Take Image' : snapshot.data['template_multi_image_picker']['ambil_gambar'], color: Colors.grey[100], borderColor: Colors.grey[500], radius: CustomStyle.boxRadius, contentColor: Colors.grey[500], paddingLeftRight: 8, heightButton: 32, paddingTopBottom: 0, icon: Icons.add,),
                  ],
                ),
              ),),
          );
        }
    );
  }
  Widget ImageCard(MultiImagePickerModel image){
    return Stack(
        children: [
      Image.file(File(image.path), width: MediaQuery.of(context).size.width/4,),
      Positioned(
          right: 0,
          top: 0,
          child: TemplateButton(
            onClick: ()=>BlocProvider.of<MultiImagePickerBloc>(context).add(DeleteImage(image)),
            label: 'x', color: Colors.transparent, contentColor: Colors.redAccent, paddingLeftRight: 6, fontSize: CustomStyle.fontSizeTitle, bold: true,))
        ],
    );
  }
}
