import 'dart:convert';

import 'package:farm_tpf/custom_model/Harvest.dart';
import 'package:farm_tpf/custom_model/Sell.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_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/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';

import '../bloc_get_harvest.dart';
import '../util_action.dart';

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

class _EditActionSellScreenState extends State<EditActionSellScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final _repository = Repository();
  GlobalKey<FormState> _formKey = GlobalKey();
  bool _autoValidate = false;
  Sell _sell = Sell();
  TextEditingController _l1Controller = TextEditingController();
  TextEditingController _l2Controller = TextEditingController();
  TextEditingController _l3Controller = TextEditingController();
  TextEditingController _removedQuantityController = TextEditingController();
  TextEditingController _descriptionController = TextEditingController();
  final _buyerController = TextEditingController();
  final _executeByController = TextEditingController();

  var pref = LocalPref();
  List<Harvest> _harvests = <Harvest>[];
  Harvest harvestValue = Harvest();
  String executeTimeView = '';
  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();
    _sell.executeDate = executeTime.convertLocalDateTimeToStringUtcDateTime();
    executeTimeView = executeTime.displayDateTime_DDMMYYYY_HHmm();
    _sell.cropId = widget.cropId;

    if (!widget.isEdit) {
      getHarvestBloc.getHarvests((data) {
        _harvests = data;
        for (var item in _harvests) {
          if (item.id == widget.harvestId) {
            harvestValue = item;
            break;
          }
        }
      }, (err) {});
    }
  }

  _validateInputs() async {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      LoadingDialog.showLoadingDialog(context);
      filePaths = Get.find<ChangeFileController>().newFiles;
      try {
        _sell.mediaDel = Get.find<ChangeFileController>().deleteFiles;
        var activitySell = jsonEncode(_sell.toJson()).toString();
        //ADD NEW
        if (_sell.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.apiAddSell, paramActivity: ConstCommon.paramsActionSell, activityAction: activitySell, 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.apiUpdateSell,
              paramActivity: ConstCommon.paramsActionSell,
              activityAction: activitySell,
              filePaths: filePaths);
        }
      } catch (e) {
        LoadingDialog.hideLoadingDialog(context);
        print(e.toString());
      }
    } else {
      _autoValidate = true;
    }
  }

  List<DropdownMenuItem<Harvest>> _buildDropMenu(List<Harvest> actions) {
    return actions
        .map((action) => DropdownMenuItem<Harvest>(
              child: Text("Mã thu hoạch " + action.id.toString()),
              value: action,
            ))
        .toList();
  }

  Widget _dropdownHarvest() {
    return StreamBuilder(
      stream: getHarvestBloc.actions,
      builder: (context, AsyncSnapshot<dynamic> snapshot) {
        if (snapshot.hasData) {
          return DropdownButtonFormField<Harvest>(
              value: harvestValue,
              hint: const Text("Mã thu hoạch"),
              onChanged: (Harvest? newValue) {
                setState(() {
                  harvestValue = newValue ?? Harvest();
                  _sell.harvestId = newValue?.id ?? -1;
                });
              },
              isExpanded: true,
              items: _buildDropMenu(_harvests));
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  Widget _btnExecuteTimePicker() {
    return FlatButton(
        padding: const EdgeInsets.only(top: 0.0, right: 0.0, bottom: 0.0, left: 0.0),
        onPressed: () {
          DatePicker.showDateTimePicker(context, showTitleActions: true, onChanged: (date) {}, onConfirm: (date) {
            setState(() {
              executeTime = date;
              _sell.executeDate = executeTime.convertLocalDateTimeToStringUtcDateTime();
              executeTimeView = executeTime.displayDateTime_DDMMYYYY_HHmm();
            });
          }, currentTime: executeTime, locale: LocaleType.vi);
        },
        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: [
                Expanded(
                    child: Text(
                  //TODO: check condition
                  executeTimeView == null ? "$executeTime" : executeTimeView,
                  style: const TextStyle(fontSize: 14.0, color: Colors.black87),
                )),
                const Icon(
                  Icons.date_range,
                  color: Colors.blue,
                ),
              ],
            )));
  }

  Widget _l1Field() {
    return WidgetTextFormFieldNumber(
      hintValue: "Số lượng/khối lượng loại 1",
      textController: _l1Controller,
      onSaved: (newValue) {
        _sell.quantityLv1 = (newValue ?? '0').parseDoubleThousand();
      },
      validator: (_) {},
      onChanged: (_) {},
    );
  }

  Widget _l2Field() {
    return WidgetTextFormFieldNumber(
      hintValue: "Số lượng/khối lượng loại 2",
      textController: _l2Controller,
      onSaved: (newValue) {
        _sell.quantityLv2 = (newValue ?? '0').parseDoubleThousand();
      },
      validator: (_) {},
      onChanged: (_) {},
    );
  }

  Widget _l3Field() {
    return WidgetTextFormFieldNumber(
      hintValue: "Số lượng/khối lượng loại 3",
      textController: _l3Controller,
      onSaved: (newValue) {
        _sell.quantityLv3 = (newValue ?? '0').parseDoubleThousand();
      },
      validator: (_) {},
      onChanged: (_) {},
    );
  }

  Widget _removedQuantityField() {
    return WidgetTextFormFieldNumber(
      hintValue: "Số lượng/khối lượng loại bỏ",
      textController: _removedQuantityController,
      onSaved: (newValue) {
        _sell.removedQuantity = (newValue ?? '0').parseDoubleThousand();
      },
      validator: (_) {},
      onChanged: (_) {},
    );
  }

  Widget _buyerField() {
    return TextFormField(
      keyboardType: TextInputType.text,
      decoration: const InputDecoration(labelText: "Khách hàng"),
      controller: _buyerController,
      onSaved: (newValue) {
        _sell.buyer = newValue ?? '';
      },
    );
  }

  Widget _descriptionField() {
    return TextFieldDescriptionWidget(
      controller: _descriptionController,
      onSaved: (newValue) {
        _sell.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.apiDetailSell,
                          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);
                              _sell = Sell.fromJson(state.item);
                              _sell.activityId = widget.activityId ?? -1;
                              _l1Controller.text = _sell.quantityLv1?.formatNumtoStringDecimal() ?? '';
                              _l2Controller.text = _sell.quantityLv2?.formatNumtoStringDecimal() ?? '';
                              _l3Controller.text = _sell.quantityLv3?.formatNumtoStringDecimal() ?? '';
                              _removedQuantityController.text = _sell.removedQuantity?.formatNumtoStringDecimal() ?? '';
                              _buyerController.text = _sell.buyer ?? "";
                              _descriptionController.text = _sell.description ?? "";
                              _executeByController.text = _sell.executeBy ?? '';

                              //select harvest
                              getHarvestBloc.getHarvests((data) {
                                _harvests = data;
                                for (var item in _harvests) {
                                  if (item.id == _sell.harvestId) {
                                    harvestValue = item;
                                    break;
                                  }
                                }
                              }, (err) {});

                              executeTime = _sell.executeDate?.convertStringServerDateTimeToLocalDateTime() ?? DateTime.now();
                              executeTimeView = executeTime.displayDateTime_DDMMYYYY_HHmm();
                              //Show media
                              if (Validators.stringNotNullOrEmpty(_sell.media ?? '')) {
                                BlocProvider.of<MediaHelperBloc>(context)
                                    .add(ChangeListMedia(items: UtilAction.convertFilePathToMedia(_sell.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(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: <Widget>[
                                      const Text(
                                        plot_action_sell,
                                        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,
                                      ),
                                      _dropdownHarvest(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _l1Field(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _l2Field(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _l3Field(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _removedQuantityField(),
                                      const SizedBox(
                                        height: 8.0,
                                      ),
                                      _buyerField(),
                                      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() {
    _l1Controller.dispose();
    _l2Controller.dispose();
    _l3Controller.dispose();
    _removedQuantityController.dispose();
    _descriptionController.dispose();
    _buyerController.dispose();
    _executeByController.dispose();
    super.dispose();
  }
}
