import 'dart:convert';

import 'package:farm_tpf/custom_model/Environment.dart';
import 'package:farm_tpf/custom_model/RequestEnvironment.dart';
import 'package:farm_tpf/data/api/app_exception.dart';
import 'package:farm_tpf/data/repository/repository.dart';
import 'package:farm_tpf/presentation/custom_widgets/app_bar_widget.dart';
import 'package:farm_tpf/presentation/custom_widgets/bloc/media_helper_bloc.dart';
import 'package:farm_tpf/presentation/custom_widgets/button_widget.dart';
import 'package:farm_tpf/presentation/custom_widgets/widget_field_time_picker.dart';
import 'package:farm_tpf/presentation/custom_widgets/widget_loading.dart';
import 'package:farm_tpf/presentation/custom_widgets/widget_media_picker.dart';
import 'package:farm_tpf/presentation/custom_widgets/widget_text_form_field.dart';
import 'package:farm_tpf/presentation/custom_widgets/widget_utils.dart';
import 'package:farm_tpf/presentation/screens/actions/bloc/action_detail_bloc.dart';
import 'package:farm_tpf/presentation/screens/actions/state_management_helper/change_file_controller.dart';
import 'package:farm_tpf/presentation/screens/actions/util_action.dart';
import 'package:farm_tpf/utils/const_common.dart';
import 'package:farm_tpf/utils/const_string.dart';
import 'package:farm_tpf/utils/const_style.dart';
import 'package:farm_tpf/utils/pref.dart';
import 'package:farm_tpf/utils/validators.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:keyboard_dismisser/keyboard_dismisser.dart';
import 'package:pattern_formatter/pattern_formatter.dart';
import 'package:farm_tpf/utils/formatter.dart';

class EditActionEnvironmentUpdate extends StatefulWidget {
  final int cropId;
  final bool isEdit;
  final int? activityId;
  EditActionEnvironmentUpdate({required this.cropId, this.isEdit = false, this.activityId});
  @override
  _EditActionEnvironmentUpdateState createState() => _EditActionEnvironmentUpdateState();
}

class _EditActionEnvironmentUpdateState extends State<EditActionEnvironmentUpdate> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final _repository = Repository();
  GlobalKey<FormState> _formKey = GlobalKey();
  bool _autoValidate = false;
  Environment _environment = Environment();
  var pref = LocalPref();
  TextEditingController _ecController = TextEditingController();
  TextEditingController _phController = TextEditingController();
  TextEditingController _ocddController = TextEditingController();
  TextEditingController _temperatureController = TextEditingController();
  TextEditingController _doController = TextEditingController();
  TextEditingController _llnController = TextEditingController();
  final _executeByController = TextEditingController();

  DateTime executeTime = DateTime.now();
  List<String> filePaths = <String>[];
  var changeFileController = Get.put(ChangeFileController());

  Future<Null> getSharedPrefs() async {
    var currentFullName = await pref.getString(DATA_CONST.CURRENT_FULL_NAME);
    _executeByController.text = currentFullName ?? "";
  }

  @override
  void initState() {
    super.initState();
    getSharedPrefs();
    changeFileController.initValue();
    _environment.cropId = widget.cropId;
  }

  _validateInputs() async {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      LoadingDialog.showLoadingDialog(context);
      filePaths = Get.find<ChangeFileController>().newFiles;
      //Create request general model
      try {
        var requestEnvironment = RequestEnvironment()
          ..cropId = _environment.cropId
          ..activityId = _environment.activityId
          ..executeDate = _environment.executeDate;
        var envDetail = <EnvDetail>[];
        envDetail.add(EnvDetail()
          ..name = "EC"
          ..index = _environment.ec);
        envDetail.add(EnvDetail()
          ..name = "pH"
          ..index = _environment.pH);
        envDetail.add(EnvDetail()
          ..name = "OCDD"
          ..index = _environment.ocdd);
        envDetail.add(EnvDetail()
          ..name = "TEMPERATURE"
          ..index = _environment.temperature);
        envDetail.add(EnvDetail()
          ..name = "DO"
          ..index = _environment.dodo);
        envDetail.add(EnvDetail()
          ..name = "LLN"
          ..index = _environment.lln);
        requestEnvironment.envDetail = envDetail;
        requestEnvironment.mediaDel = Get.find<ChangeFileController>().deleteFiles;
        var activityEnvironmentUpdate = jsonEncode(requestEnvironment.toJson()).toString();
        //ADD NEW
        if (_environment.activityId == null) {
          _repository.createAction((value) {
            LoadingDialog.hideLoadingDialog(context);
            Get.back(result: value);
            Utils.showSnackBarSuccess(message: label_add_success);
          }, (error) {
            LoadingDialog.hideLoadingDialog(context);
            Utils.showSnackBarError(message: AppException.handleError(error));
          },
              apiAddAction: ConstCommon.apiAddEnvUpdate,
              paramActivity: ConstCommon.paramsActionEnvUpdate,
              activityAction: activityEnvironmentUpdate,
              filePaths: filePaths);
        } else {
          //UPDATE
          _repository.updateAction((value) {
            LoadingDialog.hideLoadingDialog(context);
            Get.back(result: value);
            Utils.showSnackBarSuccess(message: label_update_success);
          }, (error) {
            LoadingDialog.hideLoadingDialog(context);
            Utils.showSnackBarError(message: AppException.handleError(error));
          },
              apiUpdateAction: ConstCommon.apiUpdateEnvUpdate,
              paramActivity: ConstCommon.paramsActionEnvUpdate,
              activityAction: activityEnvironmentUpdate,
              filePaths: filePaths);
        }
      } catch (e) {
        LoadingDialog.hideLoadingDialog(context);
        print(e.toString());
      }
    } else {
      _autoValidate = true;
    }
  }

  Widget _btnExecuteTimePicker() {
    return WidgetFieldDateTimePicker(
        initDateTime: executeTime,
        onUpdateDateTime: (selectedDate) {
          _environment.executeDate = selectedDate.convertLocalDateTimeToStringUtcDateTime();
        });
  }

  Widget _ecField() {
    return WidgetTextFormFieldNumber(
      hintValue: "EC",
      textController: _ecController,
      onSaved: (newValue) {
        _environment.ec = newValue ?? '';
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _phField() {
    return WidgetTextFormFieldNumber(
      hintValue: "pH",
      textController: _phController,
      onSaved: (newValue) {
        _environment.pH = newValue ?? '';
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _ocddField() {
    return WidgetTextFormFieldNumber(
      hintValue: "Nhiệt độ dung dịch",
      textController: _ocddController,
      onSaved: (newValue) {
        _environment.ocdd = newValue ?? '';
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _temperatureField() {
    return WidgetTextFormFieldNumber(
      hintValue: "Nhiệt độ môi trường",
      textController: _temperatureController,
      onSaved: (newValue) {
        _environment.temperature = newValue ?? '';
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _doField() {
    return WidgetTextFormFieldNumber(
      hintValue: "Độ ẩm",
      textController: _doController,
      onSaved: (newValue) {
        _environment.dodo = newValue ?? '';
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _llnField() {
    return WidgetTextFormFieldNumber(
      hintValue: "Lưu lượng nước",
      textController: _llnController,
      onSaved: (newValue) {
        _environment.lln = newValue ?? '';
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _executeByField() {
    return TextFormField(
      keyboardType: TextInputType.text,
      decoration: const InputDecoration(labelText: "Người thực hiện"),
      enabled: false,
      controller: _executeByController,
      onSaved: (newValue) {},
    );
  }

  @override
  Widget build(BuildContext context) => KeyboardDismisser(
          gestures: [
            GestureType.onTap,
            GestureType.onPanUpdateDownDirection,
          ],
          child: Scaffold(
              backgroundColor: Colors.white,
              key: _scaffoldKey,
              appBar: AppBarWidget(
                isBack: true,
                action: InkWell(
                  child: const Text(
                    'Huỷ',
                    style: TextStyle(color: Colors.red, fontWeight: FontWeight.normal),
                  ),
                  onTap: () {
                    if (Get.isSnackbarOpen) Get.back();
                    Get.back();
                  },
                ),
              ),
              body: KeyboardDismisser(
                  child: MultiBlocProvider(
                providers: [
                  BlocProvider<ActionDetailBloc>(
                    create: (context) => ActionDetailBloc(repository: Repository())
                      ..add(
                        FetchData(
                          isNeedFetchData: widget.isEdit,
                          apiActivity: ConstCommon.apiDetailEnvUpdate,
                          activityId: widget.activityId ?? -1,
                        ),
                      ),
                  ),
                  BlocProvider<MediaHelperBloc>(
                    create: (context) => MediaHelperBloc()..add(ChangeListMedia(items: [])),
                  )
                ],
                child: Form(
                    key: _formKey,
                    // autovalidate: _autoValidate,
                    child: SafeArea(
                      child: SingleChildScrollView(
                        child: BlocConsumer<ActionDetailBloc, ActionDetailState>(
                          listener: (context, state) async {
                            if (state is ActionDetailFailure) {
                              print("fail");
                              LoadingDialog.hideLoadingDialog(context);
                            } else if (state is ActionDetailSuccess) {
                              LoadingDialog.hideLoadingDialog(context);
                              print("success");
                              print(state.item);
                              _environment = Environment.fromJson(state.item);
                              //Parse theo API :')
                              _environment.environmentUpdates?.forEach((envDetail) {
                                switch (envDetail.tbEnvironmentalName) {
                                  case "EC":
                                    _environment.ec = envDetail.index.toString();
                                    break;
                                  case "pH":
                                    _environment.pH = envDetail.index.toString();
                                    break;
                                  case "OCDD":
                                    _environment.ocdd = envDetail.index.toString();
                                    break;
                                  case "TEMPERATURE":
                                    _environment.temperature = envDetail.index.toString();
                                    break;
                                  case "DO":
                                    _environment.dodo = envDetail.index.toString();
                                    break;
                                  case "LLN":
                                    _environment.lln = envDetail.index.toString();
                                    break;
                                  default:
                                    break;
                                }
                              });
                              _environment.activityId = widget.activityId ?? -1;
                              _ecController.text = _environment.ec?.formatStringToStringDecimal() ?? '';
                              _phController.text = _environment.pH?.formatStringToStringDecimal() ?? '';
                              _ocddController.text = _environment.ocdd?.formatStringToStringDecimal() ?? '';
                              _temperatureController.text = _environment.temperature?.formatStringToStringDecimal() ?? '';
                              _doController.text = _environment.dodo?.formatStringToStringDecimal() ?? '';
                              _llnController.text = _environment.lln?.formatStringToStringDecimal() ?? '';
                              _executeByController.text = _environment.executeBy ?? '';

                              Get.find<ChangeDateTimePicker>().change(
                                _environment.executeDate?.convertStringServerDateTimeToLocalDateTime() ?? DateTime.now(),
                              );
                              //Show media
                              if (Validators.stringNotNullOrEmpty(_environment.media ?? '')) {
                                BlocProvider.of<MediaHelperBloc>(context)
                                    .add(ChangeListMedia(items: UtilAction.convertFilePathToMedia(_environment.media ?? '')));
                              }
                            } else if (state is ActionDetailInitial) {
                              print("init");
                            } else if (state is ActionDetailLoading) {
                              print("loading");
                              LoadingDialog.showLoadingDialog(context);
                            }
                          },
                          builder: (context, state) {
                            return Column(
                              children: [
                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: <Widget>[
                                      const Text(
                                        plot_action_environment_update,
                                        style: TextStyle(fontWeight: FontWeight.w500, fontSize: 22),
                                      ),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      Container(
                                        width: double.infinity,
                                        child: const Text(
                                          "Ngày thực hiện *",
                                          style: TextStyle(color: Colors.black54, fontSize: 13.0),
                                        ),
                                      ),
                                      _btnExecuteTimePicker(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _ecField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _phField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _ocddField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _temperatureField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _doField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _llnField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _executeByField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                    ],
                                  ),
                                ),
                                Container(
                                  width: double.infinity,
                                  height: 16,
                                  color: Colors.grey[200],
                                ),
                                BlocBuilder<MediaHelperBloc, MediaHelperState>(builder: (context, state) {
                                  if (state is MediaHelperSuccess) {
                                    return WidgetMediaPicker(
                                        currentItems: state.items,
                                        onChangeFiles: (newPathFiles, deletePathFiles) async {
                                          Get.find<ChangeFileController>().change(newPathFiles, deletePathFiles);
                                        });
                                  } else {
                                    return const Center(child: CircularProgressIndicator());
                                  }
                                }),
                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: ButtonWidget(
                                      title: 'CẬP NHẬT',
                                      onPressed: () {
                                        var currentFocus = FocusScope.of(context);
                                        if (!currentFocus.hasPrimaryFocus) {
                                          currentFocus.unfocus();
                                        }
                                        _validateInputs();
                                      }),
                                ),
                              ],
                            );
                          },
                        ),
                      ),
                    )),
              ))));
  @override
  void dispose() {
    _ecController.dispose();
    _phController.dispose();
    _ocddController.dispose();
    _temperatureController.dispose();
    _doController.dispose();
    _llnController.dispose();
    _executeByController.dispose();
    super.dispose();
  }
}
