import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:peasmartcare/blocs/report_incident_create/report_incident_create_bloc.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/models/report_incident_type_model.dart';
import 'package:peasmartcare/models/user_model.dart';
import 'package:peasmartcare/pages/auth/logout.dart';
import 'package:peasmartcare/pages/report_incident/report_incident_history.dart';
import 'package:peasmartcare/widgets/empty_box.dart';
import 'package:peasmartcare/widgets/loading.dart';
import 'package:peasmartcare/widgets/sweetalert/sweetalert.dart';

class ReportIncidentForm extends StatefulWidget {
  @override
  _ReportIncidentFormState createState() => _ReportIncidentFormState();
}

class _ReportIncidentFormState extends State<ReportIncidentForm> {
  final _formKey = GlobalKey<FormState>();
  final dateFormat = DateFormat("dd/MM/yyyy");
  final numberFormat = NumberFormat("00");

  TextEditingController _detail = TextEditingController();
  DateTime _startDateVal = DateTime.now();

  String _reportIncidentTypeVal;
  String _reportIncidentTypeName;

  @override
  void dispose() {
    _detail.dispose();

    super.dispose();
  }

  @override
  void initState() {
    context.read<ReportIncidentCreateBloc>().add(ReportIncidentCreateGetData());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        _form(),
      ],
    );
  }

  Widget _form() {
    TextStyle textLabelStyle = TextStyle(
      color: Color(AppData.purpleColor),
      fontSize: 20,
      fontWeight: FontWeight.bold,
    );
    TextStyle textStyle = TextStyle(color: Color(AppData.primaryColor), fontSize: 18);
    TextStyle errortyle = TextStyle(color: Colors.orange[900], fontSize: 18, height: 0.6);
    return BlocListener<ReportIncidentCreateBloc, ReportIncidentCreateState>(
      listener: (context, state) {
        if (state is ReportIncidentCreateLoaded) {
          if (state.result != null && state.result) {
            SweetAlert.show(
              context,
              subtitle: "บันทึกข้อมูลสำเร็จ",
              style: SweetAlertStyle.success,
              showCancelButton: false,
              onPress: (bool isConfirm) {
                if (isConfirm) {
                  Navigator.pop(context);
                  Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(builder: (context) => ReportIncidentHistoryPage()),
                  );
                  return false;
                }
              },
            );
          } else if (state.result != null && !state.result) {
            SweetAlert.show(
              context,
              subtitle: "บันทึกข้อมูลไม่สำเร็จ",
              style: SweetAlertStyle.error,
            );
          }
        } else if (state is ReportIncidentCreateErrorUnauthorized) {
          Navigator.of(context).popUntil((route) => route.isFirst);
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => LogoutPage()),
          );
        }
      },
      child: BlocBuilder<ReportIncidentCreateBloc, ReportIncidentCreateState>(builder: (context, state) {
        if (state is ReportIncidentCreateLoading) {
          return Loading();
        } else if (state is ReportIncidentCreateLoaded) {
          List<ReportIncidentTypeModel> _reportIncidentTypeList = state.reportIncidentTypeList;
          UserModel user = state.user;
          return Form(
            key: _formKey,
            child: Center(
              child: Container(
                constraints: BoxConstraints(maxWidth: 500),
                child: Column(
                  children: <Widget>[
                    SizedBox(
                      height: 40,
                    ),
                    Container(
                      height: 100,
                      padding: EdgeInsets.only(left: 25, right: 25),
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        color: Color(AppData.whiteColor),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                "วันที่แจ้ง",
                                style: textLabelStyle,
                              ),
                              _startDate(),
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 30,
                    ),
                    Container(
                      height: 85,
                      padding: EdgeInsets.only(left: 30, right: 30),
                      child: DropdownButtonFormField<dynamic>(
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return "กรุณาเลือกประเภทเหตุ";
                          }
                          return null;
                        },
                        decoration: InputDecoration(
                          hintText: "ประเภทเหตุ",
                          hintStyle: textStyle,
                          labelText: "ประเภทเหตุ",
                          labelStyle: textStyle,
                          errorStyle: errortyle,
                          floatingLabelBehavior: FloatingLabelBehavior.auto,
                          filled: true,
                          fillColor: Color(AppData.whiteColor),
                          contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                          border: OutlineInputBorder(
                            borderRadius: const BorderRadius.all(
                              const Radius.circular(30),
                            ),
                          ),
                        ),
                        value: _reportIncidentTypeVal,
                        isExpanded: true,
                        onChanged: (val) {
                          ReportIncidentTypeModel reportIncidentType = _reportIncidentTypeList.singleWhere((item) => item.id == val);

                          setState(() {
                            _reportIncidentTypeVal = val;
                            _reportIncidentTypeName = reportIncidentType.name;
                          });
                        },
                        items: _reportIncidentTypeList.map<DropdownMenuItem<dynamic>>(
                          (value) {
                            return DropdownMenuItem<dynamic>(
                              value: value.id,
                              child: Text(
                                value.name,
                                style: textStyle,
                              ),
                            );
                          },
                        ).toList(),
                      ),
                    ),
                    Container(
                      height: 85,
                      padding: EdgeInsets.only(left: 30, right: 30),
                      child: TextFormField(
                        validator: (value) {
                          // if (value.isEmpty) {
                          //   return "กรุณากรอกนามสกุล";
                          // }
                          return null;
                        },
                        controller: _detail,
                        maxLines: 3,
                        style: textStyle,
                        decoration: InputDecoration(
                          hintText: "รายละเอียด",
                          hintStyle: textStyle,
                          labelText: "รายละเอียด",
                          labelStyle: textStyle,
                          errorStyle: errortyle,
                          floatingLabelBehavior: FloatingLabelBehavior.auto,
                          filled: true,
                          fillColor: Color(AppData.whiteColor),
                          contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                          border: OutlineInputBorder(
                            borderRadius: const BorderRadius.all(
                              const Radius.circular(30),
                            ),
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 30,
                    ),
                    Container(
                      height: 125,
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 25, right: 25),
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        color: Color(AppData.whiteColor),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text("ผู้แจ้ง", style: textLabelStyle),
                              Text("${user.firstname} ${user.lastname}", style: textStyle),
                              Text(user.phone, style: textStyle),
                            ],
                          ),
                        ),
                      ),
                    ),
                    Row(
                      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(
                              "บันทึก",
                              style: TextStyle(
                                fontWeight: FontWeight.w800,
                                color: Colors.white,
                                fontSize: 18,
                              ),
                            ),
                            color: Color(AppData.yellowColor),
                            onPressed: () {
                              if (_formKey.currentState.validate()) {
                                context.read<ReportIncidentCreateBloc>().add(
                                      ReportIncidentCreateOnSubmit(
                                        startDate: dateFormat.format(_startDateVal),
                                        incidentTyprId: _reportIncidentTypeVal,
                                        detail: _detail.text,
                                      ),
                                    );
                              }
                            },
                          ),
                        ),
                        SizedBox(
                          width: 20,
                        ),
                        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(
                              "ยกเลิก",
                              style: TextStyle(
                                fontWeight: FontWeight.w800,
                                color: Colors.white,
                                fontSize: 18,
                              ),
                            ),
                            color: Color(AppData.greyColor),
                            onPressed: () {
                              Navigator.pop(context);
                            },
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          );
        }

        return EmptyBox();
      }),
    );
  }

  Widget _startDate() {
    DateTime lastDayOfMonth = DateTime(DateTime.now().year, DateTime.now().month + 1, 0);
    TextStyle textStyle = TextStyle(color: Color(AppData.primaryColor), fontSize: 18);
    return Row(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.only(right: 20),
          child: Text(
            // dateFormat.format(_startDateVal),
            "${numberFormat.format(_startDateVal.day)}/${numberFormat.format(_startDateVal.month)}/${_startDateVal.year + 543}",
            style: textStyle,
          ),
        ),
        // InkWell(
        //   highlightColor: Colors.transparent,
        //   splashColor: Colors.transparent,
        //   child: Icon(
        //     Linecons.calendar,
        //     size: 25,
        //     color: Color(AppData.yellowColor),
        //   ),
        //   onTap: () async {
        //     DateTime startDate = await showRoundedDatePicker(
        //       context: context,
        //       fontFamily: AppData.notoSansThaiFont,
        //       era: EraMode.BUDDHIST_YEAR,
        //       theme: ThemeData(primarySwatch: Colors.purple),
        //       initialDate: _startDateVal,
        //       firstDate: DateTime.now().subtract(Duration(days: 1)),
        //       lastDate: DateTime(DateTime.now().year + 1, DateTime.now().month, lastDayOfMonth.day), //DateTime(DateTime.now().year + 1),
        //       borderRadius: 5,
        //     ); //as DateTime

        //     setState(() {
        //       _startDateVal = startDate ?? _startDateVal;
        //     });
        //   },
        // ),
      ],
    );
  }
}
