import 'package:echo_app/enums/global-errors.dart';
import 'package:echo_app/models/image_answers.dart';
import 'package:echo_app/screens/surveys/questions_types_widgets/check_list_question.dart';
import 'package:echo_app/screens/surveys/questions_types_widgets/date_question.dart';
import 'package:echo_app/screens/surveys/questions_types_widgets/image_question.dart';
import 'package:echo_app/screens/surveys/questions_types_widgets/multiple_value_question.dart';
import 'package:echo_app/screens/surveys/questions_types_widgets/numeric_question.dart';
import 'package:echo_app/screens/surveys/questions_types_widgets/rate_question.dart';
import 'package:echo_app/screens/surveys/questions_types_widgets/text_question.dart';
import 'package:echo_app/screens/surveys/questions_types_widgets/time_question.dart';
import 'package:echo_app/screens/surveys/questions_types_widgets/yes_no_question.dart';
import 'package:echo_app/services/survey.service.dart';
import 'package:echo_app/theme/variables.dart';
import 'package:echo_app/widgets/no_data.widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart' as GET;
import 'package:dio/dio.dart';

// import 'package:http_parser/http_parser.dart';
// import 'package:http/http.dart' as http;

// ignore: must_be_immutable
class SurveyQuestions extends StatefulWidget {
  var survey;
  var questionOptions = [];
  var question = [];
  List<ImageAnswers> imageAnswers = [];

  SurveyQuestions(this.survey, this.question, this.questionOptions);

  @override
  _SurveyQuestionsState createState() => _SurveyQuestionsState();
}

class _SurveyQuestionsState extends State<SurveyQuestions> {
  bool isValid = true;
  var _surveyService = new SurveyService();

  var answers = [];

  bool loading = false;

  fillAnswer(int fieldId, var fieldValue) {
    int i = this
        .widget
        .question
        .indexWhere((element) => element['fieldId'] == fieldId);
    setState(() {
      this.widget.question[i]['fieldValue'] = fieldValue;
    });
  }

  fillImageAnswer(
      int fieldId, List<String> files, List<String> filesName, fieldValue) {
    int serveyId = this.widget.survey['surveyId'];
    String name = "${serveyId}_${fieldId}_${filesName[0]}";
    ImageAnswers imageAnswersObj = new ImageAnswers();
    imageAnswersObj.file = files[0];
    imageAnswersObj.name = name;
    imageAnswersObj.fieldId = fieldId;
    this.widget.imageAnswers.add(imageAnswersObj);
    int i = this
        .widget
        .question
        .indexWhere((element) => element['fieldId'] == fieldId);
    setState(() {
      this.widget.question[i]['fieldValue'] = fieldValue;
    });
  }

  removeImgQuestion(int fieldId) {
    int index1 =
        this.widget.imageAnswers.indexWhere((img) => img.fieldId == fieldId);
    int index2 = this
        .widget
        .question
        .indexWhere((question) => question['fieldId'] == fieldId);
    if (index1 > -1) {
      this.widget.imageAnswers.removeAt(index1);
    }
    if (index2 > -1) {
      this.widget.question[index2]['fieldValue'] = '';
    }
  }

  onSave() async {
    var questions = [];
    questions = this.widget.question;

    for (var question in questions) {
      var fieldValue = question['fieldValue'];
      if (question['isMandatory'] && fieldValue == '') {
        setState(() {
          isValid = false;
        });
        loading = false;
        return;
      } else {
        setState(() {
          isValid = true;
        });
        this.answers.add({
          'answerID': question['fieldId'],
          'dCFID': widget.survey['dcfid'],
          'surveyID': widget.survey['surveyId'],
          'fieldTypeID': question['fieldTypeID'],
          'lOVID': question['lovid'],
          'answerName': fieldValue, //? question['fieldValue'].toString() : "",
        });
      }
    }
    if (isValid) {
      EasyLoading.show(status: 'loading'.tr);
      var response = await this._surveyService.saveSurveyAnswers(answers);

      if (response['status'] == GlobalErrors.Success.index) {
        EasyLoading.dismiss();
        EasyLoading.showSuccess("saved-successfully".tr);

        Navigator.pop(context);
        if (this.widget.imageAnswers.length > 0) {
          await this.uploadImages();
        }
        this.widget.imageAnswers = [];
        this.widget.question = [];
        CheckListQuestion.selectedOptionsTemp = [];
        loading = false;
      } else {
        loading = false;
      }
    } else {
      loading = false;
      EasyLoading.dismiss();
      CheckListQuestion.selectedOptionsTemp = [];
      EasyLoading.showError("error".tr);
    }
  }

  uploadImages() async {
    if (this.widget.imageAnswers.length > 0) {
      var formData = new FormData();
      for (var image in this.widget.imageAnswers) {
        formData.files.addAll([
          MapEntry("image",
              await MultipartFile.fromFile(image.file, filename: image.name)),
        ]);
      }
      var response = await _surveyService.uploadAnswersImages(formData);
      print(response);
    }
  }

  @override
  void dispose() {
    CheckListQuestion.selectedOptionsTemp = [];
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,

      appBar: AppBar(
         backgroundColor: Variables.color_primary,
        title: Text(widget.survey['surveyName']),
        automaticallyImplyLeading: false,
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.close),
            onPressed: () {
              CheckListQuestion.selectedOptionsTemp = [];
              Navigator.pop(context);
            },
          ),
        ],
      ),
      body: this.widget.question.length > 0
          ? Container(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Expanded(
                    flex: 10,
                    child: SingleChildScrollView(
                      child: Container(
                        padding: EdgeInsets.only(
                          top: 5,
                          bottom: 0,
                          left: 5,
                          right: 5,
                        ),
                        child: Column(
                          children: this
                              .widget
                              .question
                              .map(
                                (e) => Card(
                                    child: Container(
                                  decoration: BoxDecoration(
                                    border: Border(
                                      left: BorderSide(
                                        color: e["isMandatory"] &&
                                                this.isValid == false &&
                                                e['fieldValue'] == ''
                                            ? Colors.redAccent
                                            : Colors.white,
                                        width: 3,
                                      ),
                                    ),
                                  ),
                                  padding: EdgeInsets.all(10),
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Row(
                                        children: [
                                          Flexible(
                                            child: Text(
                                              e["questionBody"],
                                              style: Theme.of(context)
                                                  .textTheme
                                                  .headlineSmall,
                                            ),
                                          ),
                                          if (e['isMandatory'])
                                            Text(
                                              " * ",
                                              style: TextStyle(
                                                  fontSize: Variables
                                                      .headline2FontSize,
                                                  color: Colors.redAccent,
                                                  fontWeight: FontWeight.bold),
                                            ),
                                        ],
                                      ),
                                      if (e['fieldTypeID'] == 1)
                                        NumericQuestion(
                                            e['fieldId'], fillAnswer,e['fieldSubTypeID']), //Numeric
                                      if (e['fieldTypeID'] == 2)
                                        TextQuestion(
                                            e['fieldId'], fillAnswer), //Text
                                      if (e['fieldTypeID'] == 3)
                                        DateQuestion(
                                            e['fieldId'], fillAnswer), //Date
                                      if (e['fieldTypeID'] == 4)
                                        YesNoQuestion(
                                            e['fieldId'], fillAnswer), //YesNo
                                      if (e['fieldTypeID'] == 5)
                                        MultipleValueQuestion(
                                            this
                                                .widget
                                                .questionOptions
                                                .where((element) =>
                                                    element['fieldID'] ==
                                                    e['fieldId'])
                                                .toList(),
                                            e['fieldId'],
                                            e['fieldValue'].toString(),
                                            fillAnswer), //MultipleValue
                                      if (e['fieldTypeID'] == 6)
                                        CheckListQuestion(
                                            this
                                                .widget
                                                .questionOptions
                                                .where((element) =>
                                                    element['fieldID'] ==
                                                    e['fieldId'])
                                                .toList(),
                                            e['fieldId'],
                                            e['fieldValue'].toString(),
                                            fillAnswer), //CheckList
                                      if (e['fieldTypeID'] == 7)
                                        TimeQuestion(
                                            e['fieldId'], fillAnswer), //Time
                                      if (e['fieldTypeID'] == 8)
                                        ImageQuestion(
                                            e['fieldId'],
                                            fillImageAnswer,
                                            removeImgQuestion), //Image

                                      if (e['fieldTypeID'] == 10)
                                        RateQueston(
                                            e['fieldId'], fillAnswer), //Rate

                                      // if (index == this.question.length - 1)
                                      //   SizedBox(height: 10000),
                                    ],
                                  ),
                                )),
                              )
                              .toList(),
                        ),
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    // ignore: deprecated_member_use
                    child: ElevatedButton(
                      style: ButtonStyle(
                        backgroundColor: MaterialStateProperty.all(
                            Variables.color_primary),
                        shape:
                            MaterialStateProperty.all<RoundedRectangleBorder>(
                          RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(0),
                          ),
                        ),
                      ),
                      onPressed: () {
                        if (!loading) {
                          loading = true;
                          this.onSave();
                        }
                      },
                      child: Text("save".tr),
                    ),
                  ),
                  // Expanded(
                  //   flex: 1,
                  //   // ignore: deprecated_member_use
                  //   child: FlatButton(
                  //     color: Colors.redAccent,
                  //     onPressed: () {
                  //       this.uploadImages();
                  //     },
                  //     child: Text("Upload btn"),
                  //   ),
                  // ),
                ],
              ),
            )
          : NoDataWidget(),
      // floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
      // floatingActionButton: FloatingActionButton(
      //   backgroundColor: Variables.color_primary,
      //   child: Icon(Icons.check),
      //   onPressed: () {},
      // ),
    );
  }
}
