import 'dart:convert';

import 'package:farm_tpf/custom_model/Nursery.dart';
import 'package:farm_tpf/custom_model/NurseryDetail.dart';
import 'package:farm_tpf/custom_model/Supply.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/nursery/bloc/expansion_list_bloc.dart';
import 'package:farm_tpf/presentation/screens/actions/state_management_helper/change_file_controller.dart';
import 'package:farm_tpf/presentation/screens/actions/state_management_helper/change_supply.dart';
import 'package:farm_tpf/presentation/screens/resources/sc_resource_helper.dart';
import 'package:farm_tpf/utils/bloc/bloc/status_add_form_bloc.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:get/get.dart';
import 'package:get/state_manager.dart';
import 'package:keyboard_dismisser/keyboard_dismisser.dart';
import 'package:farm_tpf/utils/formatter.dart';

import '../util_action.dart';

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

class _EditActionNurseryState extends State<EditActionNurseryScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final _repository = Repository();
  GlobalKey<FormState> _formKey = GlobalKey();
  GlobalKey<FormState> _formWorkerKey = GlobalKey();
  bool _autoValidate = false;
  Nursery _nursery = Nursery();
  var pref = LocalPref();
  TextEditingController _substrateController = TextEditingController();
  TextEditingController _seedLengthController = TextEditingController();
  TextEditingController _quantityController = TextEditingController();
  TextEditingController _seedIncubationTimeController = TextEditingController();
  TextEditingController _descriptionController = TextEditingController();
  TextEditingController _workerNameController = TextEditingController();
  TextEditingController _trayNumberController = TextEditingController();
  final _executeByController = TextEditingController();
  DateTime executeTime = DateTime.now();
  List<NurseryDetail> currentNurseryDetail = <NurseryDetail>[];
  int currentIndexUpdate = -1;
  bool isResetForm = true;
  final changeSupply = Get.put(ChangeSupply());
  int selectedSupplyId = -1;
  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();
    changeSupply.initValue();
    changeFileController.initValue();
    _nursery.nurseryDetail = <NurseryDetail>[];
    _nursery.cropId = widget.cropId;
  }

  _validateInputs() async {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      LoadingDialog.showLoadingDialog(context);
      _nursery.nurseryDetail = currentNurseryDetail;
      filePaths = Get.find<ChangeFileController>().newFiles;
      _nursery.mediaDel = Get.find<ChangeFileController>().deleteFiles;
      var activityNursery = jsonEncode(_nursery.toJson()).toString();
      //ADD NEW
      if (_nursery.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.apiAddNursery,
            paramActivity: ConstCommon.paramsActionNursery,
            activityAction: activityNursery,
            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.apiUpdateNursery,
            paramActivity: ConstCommon.paramsActionNursery,
            activityAction: activityNursery,
            filePaths: filePaths);
      }
    } else {
      _autoValidate = true;
    }
  }

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

  Widget _btnSelectSubstrates() {
    return FlatButton(
        padding: const EdgeInsets.only(top: 0.0, right: 0.0, bottom: 0.0, left: 0.0),
        onPressed: () {
          Navigator.of(context)
              .push(MaterialPageRoute(
                  builder: (_) => ResourceHelperScreen(
                      titleName: "Giá thể",
                      type: ConstCommon.supplyTypeSubStrate,
                      selectedId: Get.find<ChangeSupply>().selectedSupplyId,
                      currentItems: [],
                      currentEditId: -1),
                  fullscreenDialog: false))
              .then((value) {
            if (value != null) {
              var result = value as Supply;
              _nursery.substratesId = result.id;
              changeSupply.change(result);
              print("Home: $value");
            }
          });
        },
        child: Container(
            padding: const EdgeInsets.only(top: 0.0, right: 0.0, bottom: 10.5, left: 0.0),
            decoration: const BoxDecoration(
              border: kBorderTextField,
            ),
            child: Row(
              children: [
                GetBuilder<ChangeSupply>(
                    builder: (_) => Expanded(
                        child: Text(changeSupply.selectedSupplyName == null ? "Loại giá thể" : changeSupply.selectedSupplyName.toString(),
                            style: const TextStyle(fontSize: 14.0, color: Colors.black87)))),
                const Icon(
                  Icons.arrow_drop_down,
                  color: Colors.grey,
                ),
              ],
            )));
  }

  Widget _seedLengthField() {
    return WidgetTextFormFieldNumber(
      hintValue: "Chiều dài mầm",
      textController: _seedLengthController,
      onSaved: (newValue) {
        _nursery.seedLength = (newValue ?? '0').parseDoubleThousand();
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _quantityField() {
    return WidgetTextFormFieldNumber(
      hintValue: "Số lượng hạt gieo",
      textController: _quantityController,
      onSaved: (newValue) {
        _nursery.quantity = (newValue ?? '0').parseDoubleThousand();
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _seedIncubationTimeField() {
    return WidgetTextFormFieldNumber(
      hintValue: "Thời gian ngâm hạt",
      textController: _seedIncubationTimeController,
      onSaved: (newValue) {
        _nursery.seedIncubationTime = (newValue ?? '0').parseDoubleThousand();
      },
      onChanged: (_) {},
      validator: (_) {},
    );
  }

  Widget _desciptionField() {
    return TextFieldDescriptionWidget(
        controller: _descriptionController,
        onSaved: (newValue) {
          _nursery.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) {},
    );
  }

  Widget _btnAddWorker() {
    //TODO :check flow error sua item -> xoa list -> bam nut them
    return Builder(builder: (context) {
      return BlocConsumer<StatusAddFormBloc, StatusAddFormState>(listener: (context, state) {
        if (state is Edit) {
          isResetForm = false;
          _workerNameController.text = state.nurseryDetail.workerName ?? '';
          _trayNumberController.text = state.nurseryDetail.trayNumber ?? '';
        } else if (state is Delete) {
          if (currentIndexUpdate == state.index) {
            isResetForm = true;
            _workerNameController.text = "";
            _trayNumberController.text = "";
          }
        } else {
          isResetForm = true;
          _workerNameController.text = "";
          _trayNumberController.text = "";
        }
      }, builder: (context, state) {
        return Container(
            child: Form(
          key: _formWorkerKey,
          child: Column(
            children: [
              Container(
                padding: const EdgeInsets.all(8.0),
                margin: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                    shape: BoxShape.rectangle, borderRadius: BorderRadius.circular(10), color: Colors.white, border: Border.all(color: Colors.grey)),
                child: Column(
                  children: [
                    TextFormField(
                      keyboardType: TextInputType.text,
                      controller: _workerNameController,
                      decoration: const InputDecoration(labelText: "Tên công nhân *"),
                      validator: (value) {
                        return Validators.validateNotNullOrEmpty(value ?? '', label_validate_input_empty);
                      },
                      onSaved: (newValue) {},
                    ),
                    TextFormField(
                      keyboardType: TextInputType.text,
                      controller: _trayNumberController,
                      decoration: const InputDecoration(labelText: "Ươm khây số"),
                      onSaved: (newValue) {},
                    ),
                  ],
                ),
              ),
              Container(
                margin: const EdgeInsets.all(8),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    isResetForm
                        ? Container()
                        : InkWell(
                            // shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
                            child: const Text("Huỷ"),
                            onTap: () {
                              BlocProvider.of<StatusAddFormBloc>(context).add(Reset());
                            }),
                    Expanded(
                      child: FlatButton(
                          onPressed: () {
                            if (_formWorkerKey.currentState!.validate()) {
                              _formWorkerKey.currentState!.save();
                              if (Validators.stringNotNullOrEmpty(_workerNameController.text)) {
                                var _nurseryDetail = NurseryDetail()
                                  ..workerName = _workerNameController.text
                                  ..trayNumber = _trayNumberController.text;

                                if (state is Edit) {
                                  BlocProvider.of<ExpansionListBloc>(context).add(
                                    Update(
                                      index: state.index,
                                      item: _nurseryDetail,
                                      items: state.items ?? <NurseryDetail>[],
                                    ),
                                  );
                                } else {
                                  currentNurseryDetail.insert(0, _nurseryDetail);
                                  BlocProvider.of<ExpansionListBloc>(context).add(AddNew(items: currentNurseryDetail));
                                }
                                BlocProvider.of<StatusAddFormBloc>(context).add(Reset());
                              } else {
                                Utils.showSnackBarWarning(message: "Vui lòng nhập tên công nhân");
                              }
                            } else {
                              //
                              if (!Validators.stringNotNullOrEmpty(_workerNameController.text)) {
                                Utils.showSnackBarWarning(message: "Vui lòng nhập tên công nhân");
                              }
                            }
                          },
                          child: Text(
                            (state is Edit) ? "Sửa người thực hiện" : "+ Thêm người thực hiện",
                            style: const TextStyle(color: Colors.blue),
                          )),
                    )
                  ],
                ),
              ),
            ],
          ),
        ));
      });
    });
  }

  Widget _buildListAddWorker() {
    return Builder(builder: (context) {
      return BlocBuilder<ExpansionListBloc, ExpansionListState>(builder: (context, state) {
        if (state is ExpansionListSuccess) {
          currentNurseryDetail = state.items;
          if (currentNurseryDetail.isEmpty) {
            return Container();
          }
          return Container(
              height: 70,
              child: ListView.builder(
                  physics: const ClampingScrollPhysics(),
                  scrollDirection: Axis.horizontal,
                  shrinkWrap: true,
                  itemCount: currentNurseryDetail.length,
                  itemBuilder: (context, index) {
                    return GestureDetector(
                        onTap: () {
                          print("edit worker");
                          currentIndexUpdate = index;
                          BlocProvider.of<StatusAddFormBloc>(context).add(Changed(
                              status: CRUDStatus.edit, index: index, nurseryDetail: currentNurseryDetail[index], items: currentNurseryDetail));
                        },
                        child: Card(
                            child: Stack(
                          alignment: Alignment.bottomCenter,
                          // overflow: Overflow.visible,
                          children: <Widget>[
                            Positioned(
                                child: ClipRRect(
                              borderRadius: BorderRadius.circular(8),
                              child: Container(
                                padding: const EdgeInsets.all(4),
                                width: 120,
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    const SizedBox(
                                      height: 12.0,
                                    ),
                                    Flexible(
                                      child: Text(currentNurseryDetail[index].workerName ?? "", overflow: TextOverflow.ellipsis, maxLines: 1),
                                    ),
                                    Validators.stringNotNullOrEmpty(currentNurseryDetail[index].trayNumber ?? '')
                                        ? Flexible(child: Text(currentNurseryDetail[index].trayNumber ?? ""))
                                        : const SizedBox()
                                  ],
                                ),
                              ),
                            )),
                            Positioned(
                              top: -10,
                              right: -10,
                              child: IconButton(
                                  icon: const Icon(
                                    Icons.cancel,
                                    color: Colors.redAccent,
                                  ),
                                  onPressed: () {
                                    print("Delete worker");
                                    BlocProvider.of<ExpansionListBloc>(context).add(DeleteItem(index: index, items: currentNurseryDetail));
                                    BlocProvider.of<StatusAddFormBloc>(context).add(Changed(
                                        status: CRUDStatus.delete,
                                        index: index,
                                        nurseryDetail: currentNurseryDetail[index],
                                        items: currentNurseryDetail));
                                  }),
                            )
                          ],
                        )));
                  }));
        } else if (state is ExpansionListFailure) {
          return Container();
        } else {
          return Container();
        }
      });
    });
  }

  @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<ExpansionListBloc>(
                      create: (context) => ExpansionListBloc(),
                    ),
                    BlocProvider<StatusAddFormBloc>(
                      create: (context) => StatusAddFormBloc(),
                    ),
                    BlocProvider<ActionDetailBloc>(
                      create: (context) => ActionDetailBloc(repository: Repository())
                        ..add(
                          FetchData(
                            isNeedFetchData: widget.isEdit,
                            apiActivity: ConstCommon.apiDetailNursery,
                            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);
                                    _nursery = Nursery.fromJson(state.item);
                                    _seedLengthController.text = _nursery.seedLength?.formatNumtoStringDecimal() ?? '';
                                    _quantityController.text = _nursery.quantity?.formatNumtoStringDecimal() ?? '';
                                    _seedIncubationTimeController.text = _nursery.seedIncubationTime?.formatNumtoStringDecimal() ?? '';
                                    _descriptionController.text = _nursery.description ?? '';
                                    _executeByController.text = _nursery.executeBy ?? '';
                                    Get.find<ChangeDateTimePicker>().change(
                                      _nursery.executeDate?.convertStringServerDateTimeToLocalDateTime() ?? DateTime.now(),
                                    );
                                    //Show media
                                    if (Validators.stringNotNullOrEmpty(_nursery.media ?? '')) {
                                      BlocProvider.of<MediaHelperBloc>(context)
                                          .add(ChangeListMedia(items: UtilAction.convertFilePathToMedia(_nursery.media ?? '')));
                                    }
                                    //Show worker
                                    if (_nursery.nurseryDetail != null) {
                                      if (_nursery.nurseryDetail!.length > 0) {
                                        BlocProvider.of<ExpansionListBloc>(context).add(AddNew(items: _nursery.nurseryDetail!));
                                      }
                                    }
                                    //change subStrates

                                    if (_nursery.substratesId != null) {
                                      Get.find<ChangeSupply>().changeByIdAndName(_nursery.substratesId!.toInt(), _nursery.substrateName ?? '');
                                    }
                                  } 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),
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: <Widget>[
                                            const Text(
                                              'Ươm',
                                              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,
                                            ),
                                            Container(
                                              width: double.infinity,
                                              child: const Text(
                                                "Loại giá thể",
                                                style: TextStyle(color: Colors.black54, fontSize: 13.0),
                                              ),
                                            ),
                                            _btnSelectSubstrates(),
                                            const SizedBox(
                                              height: 8.0,
                                            ),
                                            _seedLengthField(),
                                            const SizedBox(
                                              height: 8.0,
                                            ),
                                            _quantityField(),
                                            const SizedBox(
                                              height: 8.0,
                                            ),
                                            _seedIncubationTimeField(),
                                            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],
                                      ),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _buildListAddWorker(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _btnAddWorker(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      Container(
                                        width: double.infinity,
                                        height: 16,
                                        color: Colors.grey[200],
                                      ),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      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());
                                        }
                                      }),
                                      const SizedBox(
                                        height: 16,
                                      ),
                                      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();
                                              }
                                              if (!Validators.stringNotNullOrEmpty(_workerNameController.text) &&
                                                  !Validators.stringNotNullOrEmpty(_trayNumberController.text)) {
                                                _validateInputs();
                                              } else {
                                                Utils.showDialog(
                                                    title: "Tên công nhân hoặc khây trồng đang cập nhật",
                                                    message: "Bạn có muốn cập nhật?",
                                                    textConfirm: "Tiếp tục",
                                                    textCancel: "Xem lại",
                                                    onConfirm: () {
                                                      Get.back();
                                                      _validateInputs();
                                                    });
                                              }
                                            }),
                                      ),
                                    ],
                                  );
                                },
                              ),
                            ),
                          ))))));
  @override
  void dispose() {
    _substrateController.dispose();
    _seedLengthController.dispose();
    _quantityController.dispose();
    _seedIncubationTimeController.dispose();
    _descriptionController.dispose();
    _executeByController.dispose();
    super.dispose();
  }
}
