import 'dart:convert';
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mwf_app/service/assets.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/header.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/strings.dart';
import 'package:mwf_app/service/style.dart';
import 'package:mwf_app/service/alert.dart';
import 'package:mwf_app/model/visit_plan.dart';
import 'package:mwf_app/set4/service_visit_user.dart';

class RelatedDocuments extends StatefulWidget {
  final visitid;
  RelatedDocuments(this.visitid, {Key key, this.list, this.detail, this.prob})
      : super(key: key);
  Map list;
  Map detail;
  Map prob;
  @override
  _RelatedDocumentsState createState() => _RelatedDocumentsState(visitid);
}

class _RelatedDocumentsState extends State<RelatedDocuments> {
  String visitid;
  _RelatedDocumentsState(this.visitid);
  TextEditingController selectImage = TextEditingController();
  TextEditingController description = TextEditingController(); // คำอธิบาย
  var base64Image;
  int filesize = 0;
  var base64Doc;
  bool isLoading = false;

  @override
  void initState() {
    super.initState();
  }

  void openCamera() async {
    var imageCamera = await ImagePicker.pickImage(source: ImageSource.camera);
    if (imageCamera != null) {
      String base64 = base64Encode(imageCamera.readAsBytesSync());
      filesize = imageCamera.lengthSync();
      setState(() {
        selectImage.text =
            imageCamera.path.split("/")[imageCamera.path.split("/").length - 1];
        base64Image = base64;
      });
    }
  }

  _openFileExplorer() async {
    File file = await FilePicker.getFile();
    if (file != null) {
      String base64 = base64Encode(file.readAsBytesSync());
      filesize = file.lengthSync();
      setState(() {
        selectImage.text =
            file.path.split("/")[file.path.split("/").length - 1];
        base64Image = base64;
      });
    }
  }

  void openGallery() async {
    var imageGallery = await ImagePicker.pickImage(source: ImageSource.gallery);
    if (imageGallery != null) {
      String base64 = base64Encode(imageGallery.readAsBytesSync());
      filesize = imageGallery.lengthSync();
      setState(() {
        selectImage.text = imageGallery.path
            .split("/")[imageGallery.path.split("/").length - 1];
        base64Image = base64;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }
    double _width = MediaQuery.of(context).size.width;

    return Material(
      color: AppColors.bgColor,
      child: Stack(
        children: <Widget>[
          Header.header1(context),
          Header.mainMenu(context),
          Container(
            margin: EdgeInsets.only(
              top: mediaQuery(context, "h", 1000),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  AppStrings.RelatedDocuments,
                  style: AppStyle.headTextStyle(context),
                ),
              ],
            ),
          ),
          Container(
            width: _width,
            height: mediaQuery(context, 'h', 1100),
            margin: EdgeInsets.only(
              top: mediaQuery(context, 'h', 1150),
              left: mediaQuery(context, 'w', 60),
              right: mediaQuery(context, 'w', 60),
            ),
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      _buildTextMenu(context, "คำอธิบาย"),
                    ],
                  ),
                  _buildSizeBox(context),
                  Row(
                    children: <Widget>[
                      _buildRow(context),
                    ],
                  ),
                  _buildSizeBox(context),
                  Row(
                    children: <Widget>[
                      _buildTextMenu(context, "Select a file"),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      Container(
                        height: mediaQuery(context, 'h', 110),
                        width: mediaQuery(context, 'w', 720),
                        child: TextField(
                          controller: selectImage,
                          enabled: false,
                          decoration: InputDecoration(
                              border: OutlineInputBorder(
                                borderRadius: const BorderRadius.all(
                                  const Radius.circular(50.0),
                                ),
                              ),
                              filled: true,
                              counterText: "",
                              contentPadding:
                                  EdgeInsets.fromLTRB(10.0, 0.0, 20.0, 10.0),
                              hintStyle: TextStyle(color: Colors.grey[800]),
                              fillColor: Colors.white70),
                        ),
                      ),
                      Material(
                        // needed
                        color: AppColors.bgColor,
                        child: InkWell(
                          onTap: () {
                            openCamera();
                          }, // needed
                          child: Container(
                            child: SizedBox(
                              width: mediaQuery(context, "w", 107.19),
                              height: mediaQuery(context, "h", 98.12),
                              child: Image.asset(AppAssets.iconCamera),
                            ),
                          ),
                        ),
                      ),
                      Material(
                        // needed
                        color: AppColors.bgColor,
                        child: InkWell(
                          onTap: () {
                            setState(() {
                              // loading = true;
                              // openGallery();
                              _openFileExplorer();
                            });
                          }, // needed
                          child: Container(
                            child: SizedBox(
                              width: mediaQuery(context, "w", 107.19),
                              height: mediaQuery(context, "h", 98.12),
                              child: Image.asset(AppAssets.iconPicture),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                  _buildSizeBox(context),
                  _buildSizeBox(context),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      _buildButton(
                          context, "ยกเลิก", Colors.white, AppColors.color),
                      _buildButton(
                          context, "บันทึก", AppColors.color, Colors.white),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  _buildButton(context, text, bgColor, fontColor) {
    return ButtonTheme(
      minWidth: mediaQuery(context, "w", 477),
      height: mediaQuery(context, "h", 120),
      child: FlatButton(
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(
              mediaQuery(context, "w", 50),
            ),
            side: BorderSide(color: AppColors.color)),
        color: bgColor,
        textColor: Colors.red,
        padding: EdgeInsets.all(
          mediaQuery(context, "w", 10),
        ),
        onPressed: () {
          if (text == "บันทึก") {
            _saveDoc();
          } else {
            Navigator.of(context).pushReplacement(
              MaterialPageRoute(
                settings: const RouteSettings(name: '/serviceVisitUser'),
                builder: (context) => ServiceVisitUser(
                  visitid,
                  file: {
                    'files': listDocumentFile,
                  },
                  list: {'lists': widget.list},
                  detail: {'details': widget.detail},
                  prob: {'prob' : widget.prob},
                ),
              ),
            );
          }
          print(text);
        },
        child: Text(
          text,
          style: TextStyle(
            fontSize: 14.0,
            color: fontColor,
          ),
        ),
      ),
    );
  }

  _saveDoc() async {
    bool chk = await checkForm([description.text, base64Image]);

    if (chk == false) {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    } else {
      setState(() {
        isLoading = true;
      });
      var dataDoc = ListDocumentFile(
          null, // String uploadFileVisitId ;
          selectImage.text, // String userFileName;
          description.text, // String fileDescription;
          filesize, // int fileSize;
          base64Image, // String fileContent;
          null,
          );

      listDocumentFile.add(dataDoc);

      Navigator.of(context).pushReplacement(
        MaterialPageRoute(
          settings: const RouteSettings(name: '/serviceVisitUser'),
          builder: (context) => ServiceVisitUser(
            visitid,
            file: {
              'files': listDocumentFile,
            },
            list: {'lists': widget.list},
            detail: {'details': widget.detail},
            prob: {'prob' : widget.prob},
          ),
        ),
      );
      isLoading = false;
    }
  }

  _buildRow(context) {
    return Container(
      height: mediaQuery(context, 'h', 110),
      width: mediaQuery(context, 'w', 1005),
      child: TextField(
        controller: description,
        enabled: true,
        decoration: InputDecoration(
            border: OutlineInputBorder(
              borderRadius: const BorderRadius.all(
                const Radius.circular(50.0),
              ),
            ),
            filled: true,
            counterText: "",
            contentPadding: EdgeInsets.fromLTRB(10.0, 0.0, 20.0, 10.0),
            hintStyle: TextStyle(color: Colors.grey[800]),
            fillColor: Colors.white70),
      ),
    );
  }

  _buildSizeBox(context) {
    return SizedBox(
      height: mediaQuery(context, "h", 15),
    );
  }

  _buildTextMenu(context, text) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        Text(
          text + " :",
          style: TextStyle(
              fontSize: mediaQuery(context, 'h', 30), color: AppColors.Black),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }
} //class
