import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_rounded_date_picker/rounded_picker.dart';
import 'package:fluttericon/linecons_icons.dart';
import 'package:fluttericon/modern_pictograms_icons.dart';
import 'package:intl/intl.dart';
import 'package:peasmartcare/blocs/survey_question/survey_question_bloc.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/models/survey_answer_model.dart';
import 'package:peasmartcare/models/survey_choice_model.dart';
import 'package:peasmartcare/widgets/empty_box.dart';

class SurveyChoiceDateTime extends StatefulWidget {
  final List<SurveyChoiceModel> surveyChoiceList;
  final SurveyQuestionBloc bloc;
  final int currentIndex;
  final String surveyId;
  final bool isNext;
  final String customerId;
  final bool isValidate;
  final DateTime startDate;
  final DateTime endDate;
  final String defaultVelue;

  const SurveyChoiceDateTime({
    Key key,
    @required this.bloc,
    @required this.surveyChoiceList,
    @required this.currentIndex,
    @required this.surveyId,
    @required this.isNext,
    @required this.customerId,
    this.isValidate = true,
    this.startDate,
    this.endDate,
    this.defaultVelue,
  }) : super(key: key);

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

class _SurveyChoiceDateTimeState extends State<SurveyChoiceDateTime> {
  final dateFormat = DateFormat("dd/MM/yyyy");
  final timeFormat = DateFormat("HH : mm");
  final numberFormat = NumberFormat("00");
  DateTime _dateVal; // = DateTime.now();
  DateTime _timeVal;
  SurveyChoiceModel _survey = SurveyChoiceModel();
  TextEditingController _value = TextEditingController();
  TextStyle textStyle = TextStyle(color: Color(AppData.primaryColor), fontSize: 18);
  TextStyle errortyle = TextStyle(color: Colors.red[900], fontSize: 18);
  bool isDateError = false;
  bool isTimeError = false;

  @override
  void initState() {
    if (widget.surveyChoiceList.length > 0) {
      _survey = widget.surveyChoiceList[0];
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Size deviceSize = MediaQuery.of(context).size;
    return Container(
      width: double.infinity,
      child: Column(
        children: <Widget>[
          SizedBox(height: 5),
          Container(
            height: 50,
            padding: EdgeInsets.fromLTRB(20, 5, 20, 5),
            margin: EdgeInsets.fromLTRB(5, 5, 5, 5),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20),
              color: Color(AppData.whiteColor),
            ),
            child: _datePicker(),
          ),
          isDateError
              ? Align(
                  alignment: Alignment.topLeft,
                  child: Container(
                      padding: EdgeInsets.only(left: 10),
                      margin: EdgeInsets.only(bottom: 15),
                      height: 30,
                      child: Text(
                        "กรุณาเลือกวันที่",
                        style: errortyle,
                      )),
                )
              : EmptyBox(),
          Container(
            height: 50,
            padding: EdgeInsets.fromLTRB(20, 5, 20, 5),
            margin: EdgeInsets.fromLTRB(5, 5, 5, 5),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20),
              color: Color(AppData.whiteColor),
            ),
            child: _timePicker(),
          ),
          isTimeError
              ? Align(
                  alignment: Alignment.topLeft,
                  child: Container(
                      padding: EdgeInsets.only(left: 10),
                      height: 30,
                      child: Text(
                        "กรุณาเลือกเวลา",
                        style: errortyle,
                      )),
                )
              : EmptyBox(),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                padding: EdgeInsets.fromLTRB(0, 30, 0, 15),
                child: RaisedButton(
                  padding: EdgeInsets.only(top: 12, left: 30, right: 30, bottom: 12),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(7),
                  ),
                  child: Text(
                    widget.isNext ? "ถัดไป" : "ส่งแบบสำรวจ",
                    style: TextStyle(
                      fontWeight: FontWeight.w800,
                      color: Colors.white,
                      fontSize: 18,
                    ),
                  ),
                  color: Color(AppData.yellowColor),
                  onPressed: () {
                    bool _isValidate = widget.isValidate ? (_dateVal != null && _timeVal != null) : true;
                    if (_isValidate) {
                      SurveyAnswerModel answer = SurveyAnswerModel();
                      if (widget.surveyChoiceList.length > 0) {
                        setState(() {
                          isDateError = false;
                          isTimeError = false;
                        });

                        answer.questionId = _survey.questionId;
                        answer.choiceId = _survey.id;
                        answer.value = "${dateFormat.format(_dateVal)} ${timeFormat.format(_timeVal)}";
                        answer.customerId = widget.customerId;

                        widget.bloc.add(SurveyQuestionAddAnswer(
                          answer: answer,
                        ));

                        widget.bloc.add(SurveyQuestionGetCurrentQuestion(
                          currentIndex: widget.currentIndex + 1,
                        ));

                        if (!widget.isNext) {
                          widget.bloc.add(SurveyQuestionSendAnswer());
                        }
                      }
                    } else {
                      if (_dateVal == null) {
                        setState(() {
                          isDateError = true;
                        });
                      } else {
                        setState(() {
                          isDateError = false;
                        });
                      }
                      if (_timeVal == null) {
                        setState(() {
                          isTimeError = true;
                        });
                      } else {
                        setState(() {
                          isTimeError = false;
                        });
                      }
                    }
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _datePicker() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.only(right: 20),
          child: Text(_dateVal != null ? "${numberFormat.format(_dateVal.day)}/${numberFormat.format(_dateVal.month)}/${_dateVal.year + 543}" : "เลือกวันที่"),
        ),
        InkWell(
          highlightColor: Colors.transparent,
          splashColor: Colors.transparent,
          child: Icon(
            Linecons.calendar,
            size: 25,
            color: Color(AppData.yellowColor),
          ),
          onTap: () async {
            DateTime _date = await showRoundedDatePicker(
              context: context,
              fontFamily: AppData.notoSansThaiFont,
              era: EraMode.BUDDHIST_YEAR,
              theme: ThemeData(primarySwatch: Colors.purple),
              initialDate: _dateVal,
              firstDate: widget.startDate ?? DateTime.now().subtract(Duration(days: 1)),
              lastDate: widget.endDate ?? DateTime(DateTime.now().year + 1), //DateTime(DateTime.now().year + 1, DateTime.now().month, lastDayOfMonth.day)
              borderRadius: 5,
            ); //as DateTime

            setState(() {
              _dateVal = _date ?? _dateVal;
            });
          },
        ),
      ],
    );
  }

  Widget _timePicker() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.only(right: 20),
          child: Text(_timeVal != null ? timeFormat.format(_timeVal) : "เลือกเวลา"),
        ),
        InkWell(
          highlightColor: Colors.transparent,
          splashColor: Colors.transparent,
          child: Icon(
            ModernPictograms.clock,
            size: 25,
            color: Color(AppData.yellowColor),
          ),
          onTap: () async {
            DatePicker.showTimePicker(
              context,
              showTitleActions: true,
              showSecondsColumn: false,
              onChanged: (date) {
                print('change $date in time zone ' + date.timeZoneOffset.inHours.toString());
              },
              onConfirm: (date) {
                print('confirm $date');
                setState(() {
                  _timeVal = date;
                });
              },
              currentTime: DateTime.now(),
              locale: LocaleType.th,
              theme: DatePickerTheme(
                headerColor: Color(AppData.primaryColor),
                backgroundColor: Colors.purple[300],
                containerHeight: 350,
                itemHeight: 50,
                itemStyle: TextStyle(
                  color: Color(AppData.yellowColor),
                  fontWeight: FontWeight.bold,
                  fontSize: 30,
                ),
                cancelStyle: TextStyle(
                  color: Color(AppData.yellowColor),
                  fontSize: 20,
                ),
                doneStyle: TextStyle(
                  color: Color(AppData.yellowColor),
                  fontSize: 20,
                ),
              ),
            );

            // setState(() {
            //   _dateVal = _date ?? _dateVal;
            // });
          },
        ),
      ],
    );
  }
}
