import 'package:farm_tpf/custom_model/Device.dart';
import 'package:farm_tpf/custom_model/SuppliesUsing.dart';
import 'package:farm_tpf/custom_model/Supply.dart';
import 'package:farm_tpf/presentation/custom_widgets/WidgetErrorTextField.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/controller/ChangeDevice.dart';
import 'package:farm_tpf/presentation/screens/actions/controller/ChangeFieldInForm.dart';
import 'package:farm_tpf/presentation/screens/actions/controller/ChangeFormButton.dart';
import 'package:farm_tpf/presentation/screens/actions/controller/ChangeSupplyUsing.dart';
import 'package:farm_tpf/presentation/screens/actions/controller/ChangeUnit.dart';
import 'package:farm_tpf/presentation/screens/actions/resource_device_activity/sc_device_activity.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/const_common.dart';
import 'package:farm_tpf/utils/const_string.dart';
import 'package:farm_tpf/utils/const_style.dart';
import 'package:farm_tpf/utils/validators.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:farm_tpf/utils/formatter.dart';

import '../util_action.dart';

class WidgetDungSupply extends StatefulWidget {
  final List<SuppliesUsing> currentItems;
  final Function(List<SuppliesUsing> supplyChanges) onChangeSupplies;
  WidgetDungSupply({required this.currentItems, required this.onChangeSupplies});
  @override
  _WidgetDungSupplyState createState() => _WidgetDungSupplyState();
}

class _WidgetDungSupplyState extends State<WidgetDungSupply> {
  final _dosageController = TextEditingController();
  final _quantityController = TextEditingController();
  final _howToUseController = TextEditingController();
  final changeSelectedSupply = Get.put(ChangeSupply());
  final changeSupplyUsing = Get.put(ChangeSupplyUsing());
  final changeUnit = Get.put(ChangeUnit());
  final changeButton = Get.put(ChangeButtonInForm());
  final changeSelectedDevice = Get.put(ChangeDevice());
  final changeFormField = Get.put(ChangeFieldFormSupply());
  GlobalKey<FormState> _formSupplyKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    changeSelectedSupply.initValue();
    changeSelectedDevice.initValue();
    changeSupplyUsing.init(widget.currentItems);
    changeUnit.initValue();
    changeButton.resetValue();
    changeFormField.init();
  }

  Widget _buildListSupply() {
    return GetBuilder<ChangeSupplyUsing>(builder: (value) {
      widget.onChangeSupplies(value.currentItems);
      if (value.currentItems.isEmpty) {
        return Container();
      } else {
        return Container(
            height: 120,
            child: ListView.builder(
                physics: const ClampingScrollPhysics(),
                scrollDirection: Axis.horizontal,
                shrinkWrap: true,
                itemCount: value.currentItems.length,
                itemBuilder: (context, index) {
                  return GestureDetector(
                      onTap: () {
                        print("edit");
                        changeSupplyUsing.changeIndexEdit(index);
                        changeButton.updateToEdit(true);
                        var editedSupplyUsing = value.currentItems[index];
                        var editedSupply = Supply()
                          ..id = editedSupplyUsing.tbSuppliesInWarehouseId
                          ..tbSuppliesName = editedSupplyUsing.supplyName
                          ..unit = editedSupplyUsing.supplyUnit;
                        changeSelectedSupply.change(editedSupply);

                        var editedDevice = Device()
                          ..id = editedSupplyUsing.tbEquipmentOfCustomerId
                          ..name = editedSupplyUsing.equipmentName;
                        changeSelectedDevice.change(editedDevice);

                        changeUnit.updateListByUnitName(editedSupplyUsing.supplyUnit ?? '');
                        changeUnit.updateSelected(editedSupplyUsing.supplyUnit ?? '');
                        _dosageController.text = editedSupplyUsing.dosage ?? '';
                        _howToUseController.text = editedSupplyUsing.howToUse ?? '';
                        _quantityController.text = editedSupplyUsing.quantity?.formatNumtoStringDecimal() ?? '';
                      },
                      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: 150,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  const SizedBox(
                                    height: 12.0,
                                  ),
                                  Flexible(
                                    child: Text(value.currentItems[index].supplyName ?? "", overflow: TextOverflow.ellipsis, maxLines: 1),
                                  ),
                                  Validators.stringNotNullOrEmpty(value.currentItems[index].dosage ?? '')
                                      ? Flexible(child: Text("${value.currentItems[index].dosage ?? ""}"))
                                      : const SizedBox(),
                                  Validators.stringNotNullOrEmpty(value.currentItems[index].quantity?.formatNumtoStringDecimal() ?? '')
                                      ? Flexible(
                                          child: Text(
                                              "${value.currentItems[index].quantity?.formatNumtoStringDecimal() ?? ""} ${value.currentItems[index].supplyUnit ?? ""}"))
                                      : const SizedBox(),
                                  Validators.stringNotNullOrEmpty(value.currentItems[index].equipmentName ?? '')
                                      ? Flexible(child: Text("${value.currentItems[index].equipmentName ?? ""}"))
                                      : const SizedBox(),
                                  Validators.stringNotNullOrEmpty(value.currentItems[index].howToUse ?? '')
                                      ? Flexible(child: Text("${value.currentItems[index].howToUse ?? ""}"))
                                      : const SizedBox(),
                                ],
                              ),
                            ),
                          )),
                          Positioned(
                            top: -10,
                            right: -10,
                            child: IconButton(
                                icon: const Icon(
                                  Icons.cancel,
                                  color: Colors.redAccent,
                                ),
                                onPressed: () {
                                  changeSupplyUsing.deleteSupply(index);
                                }),
                          )
                        ],
                      )));
                }));
      }
    });
  }

  Widget _btnSelectSubstrates() {
    return GetBuilder<ChangeSupply>(builder: (data) {
      return FlatButton(
          padding: const EdgeInsets.only(top: 0.0, right: 0.0, bottom: 0.0, left: 0.0),
          onPressed: () {
            var currentIndexEdit = changeSupplyUsing.currentIndex;
            Navigator.of(context)
                .push(MaterialPageRoute(
                    builder: (_) => ResourceHelperScreen(
                          titleName: "Phân bón",
                          type: ConstCommon.supplyTypeDung,
                          selectedId: changeSelectedSupply.selectedSupplyId,
                          currentItems: changeSupplyUsing.currentItems,
                          currentEditId:
                              (currentIndexEdit >= 0) ? changeSupplyUsing.currentItems[currentIndexEdit].tbSuppliesInWarehouseId ?? -1 : -1,
                        ),
                    fullscreenDialog: false))
                .then((value) {
              if (value != null) {
                var result = value as Supply;
                changeSelectedSupply.change(result);
                changeUnit.updateListByUnitName(result.unit ?? '');
                changeFormField.change(true);
              }
            });
          },
          child: GetBuilder<ChangeSupply>(builder: (_) {
            var isValid = changeSelectedSupply.isValid;
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                    padding: const EdgeInsets.only(top: 0.0, right: 0.0, bottom: 10.5, left: 0.0),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          width: 1,
                          color: isValid ? Colors.grey : Colors.red,
                        ),
                      ),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Tên thương mại *',
                          style: TextStyle(fontSize: 13, fontWeight: FontWeight.normal, color: isValid ? Colors.black54 : Colors.red[600]),
                        ),
                        Row(
                          children: [
                            Expanded(
                                child: Text(changeSelectedSupply.selectedSupplyName ?? "Tên thương mại",
                                    style: const TextStyle(fontSize: 14.0, color: Colors.black87))),
                            const Icon(
                              Icons.arrow_drop_down,
                              color: Colors.grey,
                            ),
                          ],
                        )
                      ],
                    )),
                isValid ? const SizedBox() : WidgetErrorTextField()
              ],
            );
          }));
    });
  }

  Widget _btnSelectDevice() {
    return GetBuilder<ChangeDevice>(builder: (data) {
      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: (_) => ListDeviceActivity(selectedId: changeSelectedDevice.selectedDeviceId), fullscreenDialog: false))
                .then((value) {
              if (value != null) {
                var result = value as Device;
                changeSelectedDevice.change(result);
                changeFormField.change(true);
              }
            });
          },
          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(changeSelectedDevice.selectedDeviceName ?? "Thiết bị",
                              style: const TextStyle(fontSize: 14.0, color: Colors.black87)))),
                  const Icon(
                    Icons.arrow_drop_down,
                    color: Colors.grey,
                  ),
                ],
              )));
    });
  }

  Widget _dropdownUnitTypes() {
    return GetBuilder<ChangeUnit>(builder: (data) {
      return DropdownButtonFormField<String>(
        itemHeight: 100,
        value: data.selectedUnit.isEmpty ? null : data.selectedUnit,
        items: data.currentUnits
            .map((label) => DropdownMenuItem(
                  child: Text(label),
                  value: label,
                ))
            .toList(),
        onChanged: (value) {
          var currentQuantity = _quantityController.text;
          num assignValue = currentQuantity.parseDoubleThousand();
          if (assignValue != null) {
            var oldSelected = data.selectedUnit;
            if (oldSelected == value) {
            } else {
              assignValue = UtilAction.convertUnit(inputValue: assignValue, oldUnit: oldSelected, newUnit: value ?? '');
            }
            _quantityController.text = assignValue.formatNumtoStringDecimal();
          }
          changeUnit.updateSelected(value ?? '');
        },
      );
    });
  }

  _quantityField() {
    return WidgetTextFormFieldNumber(
      hintValue: "Tổng lượng sử dụng *",
      textController: _quantityController,
      validator: (String? value) {
        // return Validators.validateNotNullOrEmpty(value, label_validate_input_empty);
      },
      onChanged: (value) {
        if (!Validators.stringNotNullOrEmpty(value) &&
            !Validators.stringNotNullOrEmpty(_howToUseController.text) &&
            !Validators.stringNotNullOrEmpty(_dosageController.text) &&
            Get.find<ChangeSupply>().selectedSupplyId <= 0 &&
            changeSelectedDevice.selectedDeviceId <= 0) {
          changeFormField.change(false);
        } else {
          changeFormField.change(true);
        }
      },
      onSaved: (_) {},
    );
  }

  _buttonInForm() {
    return GetBuilder<ChangeButtonInForm>(builder: (_) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _.isEdit
              ? InkWell(
                  // shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
                  child: const Text("Huỷ"),
                  onTap: () {
                    changeButton.resetValue();
                    _resetForm();
                    _hidenKeyboard(context);
                  })
              : const SizedBox(),
          _.isEdit
              ? Expanded(
                  child: FlatButton(
                      onPressed: () {
                        if (_formSupplyKey.currentState!.validate()) {
                          _formSupplyKey.currentState!.save();
                          if (changeSelectedSupply.selectedSupplyId <= 0) {
                            changeSelectedSupply.changeValid(false);
                          } else {
                            changeSelectedSupply.changeValid(true);
                          }
                          var currentSupply = changeSelectedSupply.currentSupply;
                          var currentDevice = changeSelectedDevice.currentDevice;
                          var currentQuantity = _quantityController.text.parseDoubleThousand();
                          if (currentSupply.id != null && (currentQuantity ?? 0) > 0) {
                            var quantityWithCurrentSupplyUnit = UtilAction.convertUnit(
                              inputValue: currentQuantity,
                              oldUnit: changeUnit.selectedUnit,
                              newUnit: changeSelectedSupply.currentSupply.unit ?? '',
                            );
                            var newSup = SuppliesUsing()
                              ..dosage = _dosageController.text
                              ..howToUse = _howToUseController.text
                              ..quantity = quantityWithCurrentSupplyUnit
                              ..tbSuppliesInWarehouseId = currentSupply.id
                              ..suppliesInWarehouseId = currentSupply.id
                              ..supplyName = currentSupply.tbSuppliesName
                              ..tbEquipmentOfCustomerId = currentDevice.id
                              ..equipmentOfCustomerId = currentDevice.id
                              ..equipmentName = currentDevice.name
                              ..supplyUnit = currentSupply.unit
                              ..unit = currentSupply.unit;
                            changeSupplyUsing.editSupply(changeSupplyUsing.currentIndex, newSup);
                            _resetForm();
                            _hidenKeyboard(context);
                          } else if (currentSupply.id == null || ((currentQuantity ?? 0) <= 0)) {
                            Utils.showSnackBarWarning(message: "Vui lòng nhập vật tư và số lượng");
                          }
                        } else {
                          Utils.showSnackBarWarning(message: "Vui lòng nhập vật tư và số lượng");
                          if (changeSelectedSupply.selectedSupplyId <= 0) {
                            changeSelectedSupply.changeValid(false);
                          } else {
                            changeSelectedSupply.changeValid(true);
                          }
                        }
                      },
                      child: const Text(
                        "Sửa phân bón",
                        style: TextStyle(color: Colors.blue),
                      )),
                )
              : Expanded(
                  child: FlatButton(
                      onPressed: () {
                        if (_formSupplyKey.currentState!.validate()) {
                          _formSupplyKey.currentState!.save();
                          if (changeSelectedSupply.selectedSupplyId <= 0) {
                            changeSelectedSupply.changeValid(false);
                          } else {
                            changeSelectedSupply.changeValid(true);
                          }
                          var currentSupply = changeSelectedSupply.currentSupply;
                          var currentDevice = changeSelectedDevice.currentDevice;
                          var currentQuantity = _quantityController.text.parseDoubleThousand();
                          if (currentSupply.id != null && (currentQuantity ?? 0) > 0) {
                            var quantityWithCurrentSupplyUnit = UtilAction.convertUnit(
                              inputValue: currentQuantity,
                              oldUnit: changeUnit.selectedUnit,
                              newUnit: changeSelectedSupply.currentSupply.unit ?? '',
                            );
                            var newSup = SuppliesUsing()
                              ..dosage = _dosageController.text
                              ..howToUse = _howToUseController.text
                              ..quantity = quantityWithCurrentSupplyUnit
                              ..tbSuppliesInWarehouseId = currentSupply.id
                              ..suppliesInWarehouseId = currentSupply.id
                              ..supplyName = currentSupply.tbSuppliesName
                              ..supplyUnit = currentSupply.unit
                              ..tbEquipmentOfCustomerId = currentDevice.id
                              ..equipmentOfCustomerId = currentDevice.id
                              ..equipmentName = currentDevice.name
                              ..unit = currentSupply.unit;
                            changeSupplyUsing.addSupply(newSup);
                            _resetForm();
                            _hidenKeyboard(context);
                          } else if (currentSupply.id == null || ((currentQuantity ?? 0) <= 0)) {
                            Utils.showSnackBarWarning(message: "Vui lòng nhập vật tư và số lượng");
                          }
                        } else {
                          Utils.showSnackBarWarning(message: "Vui lòng nhập vật tư và số lượng");
                          if (changeSelectedSupply.selectedSupplyId <= 0) {
                            changeSelectedSupply.changeValid(false);
                          } else {
                            changeSelectedSupply.changeValid(true);
                          }
                          //
                        }
                      },
                      child: const Text(
                        "+ Thêm phân bón",
                        style: TextStyle(color: Colors.blue),
                      )),
                )
        ],
      );
    });
  }

  Widget _formEdit() {
    return Form(
      key: _formSupplyKey,
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.all(8.0),
            margin: const EdgeInsets.all(8.0),
            decoration: BoxDecoration(
              shape: BoxShape.rectangle,
              borderRadius: BorderRadius.circular(10),
              color: Colors.white,
              border: Border.all(
                color: Colors.grey,
              ),
            ),
            child: Column(
              children: [
                _btnSelectSubstrates(),
                TextFormField(
                  keyboardType: TextInputType.text,
                  controller: _dosageController,
                  decoration: const InputDecoration(labelText: "Liều lượng sử dụng"),
                  onSaved: (newValue) {},
                  onChanged: (value) {
                    if (!Validators.stringNotNullOrEmpty(_quantityController.text) &&
                        !Validators.stringNotNullOrEmpty(_howToUseController.text) &&
                        !Validators.stringNotNullOrEmpty(value) &&
                        Get.find<ChangeSupply>().selectedSupplyId <= 0 &&
                        changeSelectedDevice.selectedDeviceId <= 0) {
                      changeFormField.change(false);
                    } else {
                      changeFormField.change(true);
                    }
                  },
                ),
                Row(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                        flex: 2,
                        child: Container(
                          height: 82,
                          child: _quantityField(),
                        ),
                      ),
                      const SizedBox(
                        width: 16.0,
                      ),
                      Expanded(
                          flex: 1,
                          child: Align(
                            alignment: Alignment.bottomCenter,
                            child: _dropdownUnitTypes(),
                          )),
                    ]),
                Container(
                  width: double.infinity,
                  child: const Text(
                    "Thiết bị",
                    style: TextStyle(color: Colors.black54, fontSize: 13.0),
                  ),
                ),
                _btnSelectDevice(),
                TextFormField(
                  keyboardType: TextInputType.text,
                  controller: _howToUseController,
                  decoration: const InputDecoration(labelText: "Phương pháp sử dụng"),
                  onSaved: (newValue) {},
                  onChanged: (value) {
                    if (!Validators.stringNotNullOrEmpty(_quantityController.text) &&
                        !Validators.stringNotNullOrEmpty(value) &&
                        !Validators.stringNotNullOrEmpty(_dosageController.text) &&
                        Get.find<ChangeSupply>().selectedSupplyId <= 0 &&
                        changeSelectedDevice.selectedDeviceId <= 0) {
                      changeFormField.change(false);
                    } else {
                      changeFormField.change(true);
                    }
                  },
                ),
              ],
            ),
          ),
          _buttonInForm()
        ],
      ),
    );
  }

  _resetForm() {
    changeSupplyUsing.changeIndexEdit(-1);
    changeButton.resetValue();
    _dosageController.text = "";
    _howToUseController.text = "";
    _quantityController.text = "";
    changeUnit.initValue();
    changeSelectedSupply.initValue();
    changeSelectedDevice.initValue();
    changeFormField.change(false);
  }

  _hidenKeyboard(BuildContext context) {
    var currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus) {
      currentFocus.unfocus();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        const Padding(
          padding: EdgeInsets.all(8.0),
          child: Align(
            alignment: Alignment.centerLeft,
            child: Text(
              'Phân bón',
              style: TextStyle(color: Colors.black54, fontSize: 14),
            ),
          ),
        ),
        _buildListSupply(),
        const SizedBox(
          height: 8.0,
        ),
        _formEdit(),
        const SizedBox(
          height: 8.0,
        ),
      ],
    );
  }
}
