import 'dart:convert';

import 'package:farm_tpf/custom_model/CropStatus.dart';
import 'package:farm_tpf/custom_model/RequestGeneralModel.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_field_description.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 EditActionCropStatusScreen extends StatefulWidget {
  final int cropId;
  final bool isEdit;
  final int? activityId;
  EditActionCropStatusScreen({required this.cropId, this.isEdit = false, this.activityId});
  @override
  _EditActionCropStatusScreenState createState() => _EditActionCropStatusScreenState();
}

class _EditActionCropStatusScreenState extends State<EditActionCropStatusScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final _repository = Repository();
  GlobalKey<FormState> _formKey = GlobalKey();
  bool _autoValidate = false;
  CropStatus _cropStatus = CropStatus();
  var pref = LocalPref();
  TextEditingController _cropRateController = TextEditingController();
  TextEditingController _numTreeController = TextEditingController();
  TextEditingController _heightOfTreeController = TextEditingController();
  TextEditingController _numberOfLeafController = TextEditingController();
  TextEditingController _leafSizeController = TextEditingController();
  TextEditingController _leafColorController = TextEditingController();
  TextEditingController _abilityProduceBudsController = TextEditingController();
  TextEditingController _internodeLengthController = TextEditingController();
  TextEditingController _descriptionController = 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();
    _cropStatus.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 generalModel = RequestGeneralModel()
          ..cropId = _cropStatus.cropId
          ..activityId = _cropStatus.activityId
          ..description = _cropStatus.description
          ..executeDate = _cropStatus.executeDate;
        var generalDetail = <ObjectUpdateDetail>[];
        generalDetail.add(ObjectUpdateDetail()
          ..name = "TY_LE_CAY_TRONG"
          ..index = _cropStatus.cropRate);
        generalDetail.add(ObjectUpdateDetail()
          ..name = "SO_LUONG_LEN_CAY"
          ..index = _cropStatus.numberOfTreeToGrow);
        generalDetail.add(ObjectUpdateDetail()
          ..name = "CHIEU_CAO_CAY"
          ..index = _cropStatus.heightOfTree);
        generalDetail.add(ObjectUpdateDetail()
          ..name = "SO_LA"
          ..index = _cropStatus.numberOfLeaf);
        generalDetail.add(ObjectUpdateDetail()
          ..name = "KICH_THUOC_LA"
          ..index = _cropStatus.leafSize);
        generalDetail.add(ObjectUpdateDetail()
          ..name = "MAU_LA"
          ..index = _cropStatus.leafColor);
        generalDetail.add(ObjectUpdateDetail()
          ..name = "DAI_DOT_THAN"
          ..index = _cropStatus.internodeLength);
        generalDetail.add(ObjectUpdateDetail()
          ..name = "KHA_NANG_SINH_CHOI"
          ..index = _cropStatus.abilityProduceBuds);
        generalModel.objectUpdateDetail = generalDetail;
        generalModel.mediaDel = Get.find<ChangeFileController>().deleteFiles;
        var activityCropStatus = jsonEncode(generalModel.toJson()).toString();
        //ADD NEW
        if (_cropStatus.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.apiAddCropStatus,
              paramActivity: ConstCommon.paramsActionCropStatus,
              activityAction: activityCropStatus,
              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.apiUpdateCropStatus,
              paramActivity: ConstCommon.paramsActionCropStatus,
              activityAction: activityCropStatus,
              filePaths: filePaths);
        }
      } catch (e) {
        LoadingDialog.hideLoadingDialog(context);
        Utils.showSnackBarError(message: exception_common);
      }
    } else {
      _autoValidate = true;
    }
  }

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

  Widget _cropRateField() {
    return WidgetTextFormFieldNumber(
      hintValue: "Tỉ lệ lên cây",
      textController: _cropRateController,
      onSaved: (newValue) {
        _cropStatus.cropRate = newValue ?? '';
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _numTreeField() {
    return WidgetTextFormFieldNumber(
      hintValue: "Số lượng lên cây",
      textController: _numTreeController,
      onSaved: (newValue) {
        _cropStatus.numberOfTreeToGrow = newValue ?? '';
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _hightOfTreeField() {
    return WidgetTextFormFieldNumber(
      hintValue: "Chiều cao cây",
      textController: _heightOfTreeController,
      onSaved: (newValue) {
        _cropStatus.heightOfTree = newValue ?? '';
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _numberOfLeafField() {
    return WidgetTextFormFieldNumber(
      hintValue: "Số lá",
      textController: _numberOfLeafController,
      onSaved: (newValue) {
        _cropStatus.numberOfLeaf = newValue ?? '';
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _leafSizeField() {
    return WidgetTextFormFieldNumber(
      hintValue: "Kích thước lá",
      textController: _leafSizeController,
      onSaved: (newValue) {
        _cropStatus.leafSize = newValue ?? '';
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _leafColorField() {
    return TextFormField(
      keyboardType: TextInputType.text,
      decoration: const InputDecoration(labelText: "Màu lá"),
      controller: _leafColorController,
      onSaved: (newValue) {
        _cropStatus.leafColor = newValue ?? '';
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _internodeLengthField() {
    return WidgetTextFormFieldNumber(
      hintValue: "Dài đốt thân",
      textController: _internodeLengthController,
      onSaved: (newValue) {
        _cropStatus.internodeLength = newValue ?? '';
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _abilityProduceBudsField() {
    return TextFormField(
      keyboardType: TextInputType.text,
      decoration: const InputDecoration(labelText: "Khả năng sinh chồi"),
      controller: _abilityProduceBudsController,
      onSaved: (newValue) {
        _cropStatus.abilityProduceBuds = newValue ?? '';
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _desciptionField() {
    return TextFieldDescriptionWidget(
        controller: _descriptionController,
        onSaved: (newValue) {
          _cropStatus.description = newValue;
        });
  }

  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.apiDetailCropStatus, 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);
                              _cropStatus = CropStatus.fromJson(state.item);
                              _cropStatus.activityId = widget.activityId ?? -1;
                              _cropRateController.text = _cropStatus.cropRate?.formatStringToStringDecimal() ?? '';
                              _numTreeController.text = _cropStatus.numberOfTreeToGrow?.formatStringToStringDecimal() ?? '';
                              _heightOfTreeController.text = _cropStatus.heightOfTree?.formatStringToStringDecimal() ?? '';
                              _numberOfLeafController.text = _cropStatus.numberOfLeaf?.formatStringToStringDecimal() ?? '';
                              _leafSizeController.text = _cropStatus.leafSize?.formatStringToStringDecimal() ?? '';
                              _leafColorController.text = _cropStatus.leafColor ?? "";
                              _abilityProduceBudsController.text = _cropStatus.abilityProduceBuds ?? "";
                              _internodeLengthController.text = _cropStatus.internodeLength?.formatStringToStringDecimal() ?? '';
                              _descriptionController.text = _cropStatus.description ?? "";
                              _executeByController.text = _cropStatus.executeBy ?? "";

                              Get.find<ChangeDateTimePicker>().change(
                                _cropStatus.executeDate?.convertStringServerDateTimeToLocalDateTime() ?? DateTime.now(),
                              );
                              //Show media
                              if (Validators.stringNotNullOrEmpty(_cropStatus.media ?? '')) {
                                BlocProvider.of<MediaHelperBloc>(context)
                                    .add(ChangeListMedia(items: UtilAction.convertFilePathToMedia(_cropStatus.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_crop_status,
                                        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,
                                      ),
                                      _cropRateField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _numTreeField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _hightOfTreeField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _numberOfLeafField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _leafSizeField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _leafColorField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _internodeLengthField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _abilityProduceBudsField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _desciptionField(),
                                      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) {
                                    print("length: " + state.items.length.toString());
                                    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() {
    _cropRateController.dispose();
    _numTreeController.dispose();
    _heightOfTreeController.dispose();
    _numberOfLeafController.dispose();
    _leafSizeController.dispose();
    _leafColorController.dispose();
    _abilityProduceBudsController.dispose();
    _internodeLengthController.dispose();
    _descriptionController.dispose();
    _executeByController.dispose();
    super.dispose();
  }
}
