import 'dart:convert';

import 'package:farm_tpf/custom_model/UseWater.dart';
import 'package:farm_tpf/custom_model/WaterType.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/utils/const_common.dart';
import 'package:farm_tpf/utils/const_string.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:keyboard_dismisser/keyboard_dismisser.dart';
import 'package:farm_tpf/utils/formatter.dart';

import '../util_action.dart';

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

class _EditActionUseWaterScreenState extends State<EditActionUseWaterScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final _repository = Repository();
  GlobalKey<FormState> _formKey = GlobalKey();
  bool _autoValidate = false;
  UseWater _useWater = UseWater();
  var pref = LocalPref();
  TextEditingController _amountController = TextEditingController();
  TextEditingController _descriptionController = TextEditingController();
  final _executeByController = TextEditingController();

  DateTime executeTime = DateTime.now();
  List<String> filePaths = <String>[];
  var changeFileController = Get.put(ChangeFileController());
  var changeRadio = Get.put(ChangeRadioButton());
  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();
    changeRadio.init(widget.isEdit);
    _useWater.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 {
        _useWater.waterType = changeRadio.selectedWaterType.waterTypeName;
        _useWater.mediaDel = Get.find<ChangeFileController>().deleteFiles;
        var activityUseWater = jsonEncode(_useWater.toJson()).toString();
        //ADD NEW
        if (_useWater.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.apiAddUserWater,
              paramActivity: ConstCommon.paramsActionUseWater,
              activityAction: activityUseWater,
              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.apiUpdateUseWater,
              paramActivity: ConstCommon.paramsActionUseWater,
              activityAction: activityUseWater,
              filePaths: filePaths);
        }
      } catch (e) {
        LoadingDialog.hideLoadingDialog(context);
        print(e.toString());
      }
    } else {
      _autoValidate = true;
    }
  }

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

  Widget _amountField() {
    return WidgetTextFormFieldNumber(
      hintValue: "Thể tích nước sử dụng",
      textController: _amountController,
      onSaved: (newValue) {
        _useWater.amount = (newValue ?? '0').parseDoubleThousand();
      },
      validator: (v) {},
      onChanged: (_) {},
    );
  }

  Widget _descriptionField() {
    return TextFieldDescriptionWidget(
      controller: _descriptionController,
      onSaved: (newValue) {
        _useWater.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 _typeWater() {
    return GetBuilder<ChangeRadioButton>(
      builder: (value) {
        if (value._waterTypes != null) {
          return Container(
            child: ListView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemBuilder: (context, index) {
                return GestureDetector(
                    child: RadioListTile(
                        title: Text(value._waterTypes[index].waterTypeDescription ?? ""),
                        value: value._waterTypes[index],
                        groupValue: value.selectedWaterType == null ? null : value.selectedWaterType,
                        onChanged: (WaterType? value) {
                          changeRadio.changeSelected(value ?? WaterType());
                        }),
                    onTap: () {});
              },
              itemCount: value._waterTypes.length,
            ),
          );
        } 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<ActionDetailBloc>(
                    create: (context) => ActionDetailBloc(repository: Repository())
                      ..add(
                        FetchData(isNeedFetchData: widget.isEdit, apiActivity: ConstCommon.apiDetailUseWater, 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) {
                              LoadingDialog.hideLoadingDialog(context);
                            } else if (state is ActionDetailSuccess) {
                              LoadingDialog.hideLoadingDialog(context);
                              print(state.item);
                              _useWater = UseWater.fromJson(state.item);
                              _amountController.text = _useWater.amount?.formatNumtoStringDecimal() ?? '';
                              _descriptionController.text = _useWater.description ?? "";
                              _executeByController.text = _useWater.executeBy ?? '';

                              Get.find<ChangeDateTimePicker>().change(
                                _useWater.executeDate?.convertStringServerDateTimeToLocalDateTime() ?? DateTime.now(),
                              );

                              changeRadio.initWithSelectedByName(_useWater.waterType ?? '');

                              //Show media
                              if (Validators.stringNotNullOrEmpty(_useWater.media ?? '')) {
                                BlocProvider.of<MediaHelperBloc>(context)
                                    .add(ChangeListMedia(items: UtilAction.convertFilePathToMedia(_useWater.media ?? '')));
                              }
                            } else if (state is ActionDetailInitial) {
                            } else if (state is ActionDetailLoading) {
                              LoadingDialog.showLoadingDialog(context);
                            }
                          },
                          builder: (context, state) {
                            return Column(
                              children: [
                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Column(
                                    children: <Widget>[
                                      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,
                                      ),
                                      _typeWater(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _amountField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _descriptionField(),
                                      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() {
    _amountController.dispose();
    _descriptionController.dispose();
    _executeByController.dispose();
    super.dispose();
  }
}

class ChangeRadioButton extends GetxController {
  late List<WaterType> _waterTypes;
  late WaterType selectedWaterType;
  Future<void> init(bool isEditScreen) async {
    //init if is NOT edit screen
    if (!isEditScreen) {
      selectedWaterType = WaterType();
      _waterTypes = <WaterType>[];
      //Get action types
      var _repo = Repository();
      try {
        var response = await _repo.getWaterTypes();
        if (response.length != null) {
          _waterTypes = response;
          _waterTypes.forEach((element) {
            if (element.waterTypeName == "TYPE_WATERING_PLANTS") {
              selectedWaterType = element;
            }
          });

          update();
        }
      } catch (error) {
        print(error.toString());
      }
    }
  }

  void changeSelected(WaterType selected) {
    selectedWaterType = selected;
    update();
  }

  //init and selected item
  Future<void> initWithSelectedByName(String waterTypeName) async {
    var _repo = Repository();
    try {
      var response = await _repo.getWaterTypes();
      if (response.length != null) {
        _waterTypes = response;
        _waterTypes.forEach((element) {
          if (element.waterTypeName == waterTypeName) {
            selectedWaterType = element;
          }
        });
        update();
      }
    } catch (error) {
      print(error.toString());
    }
  }
}
