import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:farm_tpf/presentation/custom_widgets/widget_utils.dart';
import 'package:farm_tpf/presentation/screens/codes/models/stamp_request.dart';
import 'package:farm_tpf/presentation/screens/codes/models/stamp_type.dart';
import 'package:farm_tpf/utils/formatter.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../custom_model/TbCropDTO.dart';
import '../../../../data/api/app_exception.dart';
import '../../../../data/repository/repository.dart';
import '../../../../models/item_dropdown.dart';
import '../../../../utils/utils.dart';

part 'create_stamp_state.dart';

class CreateStampCubit extends Cubit<CreateStampState> {
  CreateStampCubit() : super(CreateStampInitial());
  final repository = Repository();
  final formKey = GlobalKey<FormState>();
  final descriptionCtl = TextEditingController();
  final quantityCtl = TextEditingController();
  final expiredDateCtl = TextEditingController();
  final productNameCtl = TextEditingController();
  var stampTypeRaws = <StampType>[];
  var stampTypes = ValueNotifier(<ItemDropDown>[]);
  var selectedStampType = ValueNotifier('');

  var plotRaws = <TbCropDTO>[];
  var plots = ValueNotifier(<ItemDropDown>[]);
  var selectedPlot = ValueNotifier('');
  // var existedCreateStamp = UpdateCreateStamp();

  void dispose() {
    descriptionCtl.dispose();
    quantityCtl.dispose();
    expiredDateCtl.dispose();
    productNameCtl.dispose();
  }

  Future<void> preparedData() async {
    try {
      await Future.delayed(const Duration(seconds: 0));
      emit(CreateStampLoading());
      stampTypeRaws = await repository.stampTypes();
      stampTypes.value = stampTypeRaws
          .map(
            (e) => ItemDropDown(key: e.id?.toString(), value: e.exampleStampName),
          )
          .toList();

      plotRaws = await repository.getPlotsWithoutPaging();
      plots.value = plotRaws
          .map(
            (e) => ItemDropDown(key: e.id?.toString(), value: e.code),
          )
          .toList();
      emit(CreateStampPrepareDataSuccessful());
    } catch (e) {
      emit(CreateStampFailure(AppException.handleError(e)));
    }
  }

  Future<void> onSubmit() async {
    if (formKey.currentState!.validate()) {
      var requestStamp = RequestStamp();
      var expiredDate = DateTime.now().add(Duration(days: int.tryParse(expiredDateCtl.text) ?? 0));
      requestStamp
        ..tBCropId = int.tryParse(selectedPlot.value)
        ..productName = productNameCtl.text
        ..description = descriptionCtl.text
        ..quantity = int.tryParse(quantityCtl.text) ?? 0
        ..expiredDate = expiredDate.convertLocalDateTimeToStringUtcDateTime()
        ..tbExampleStampId = int.tryParse(selectedStampType.value);
      if (selectedPlot.value.isEmpty) {
        Utils.showSnackBarWarning(message: 'Vui lòng chọn lô');
        return;
      } else if (descriptionCtl.text.trim().isEmpty) {
        Utils.showSnackBarWarning(message: 'Vui lòng nhập mô tả');
        return;
      } else if (productNameCtl.text.trim().isEmpty) {
        Utils.showSnackBarWarning(message: 'Vui lòng nhập tên sản phẩm');
        return;
      } else if ((int.tryParse(quantityCtl.text) ?? 0) == 0) {
        Utils.showSnackBarWarning(message: 'Vui lòng nhập số lượng tem');
        return;
      } else if ((int.tryParse(expiredDateCtl.text) ?? 0) == 0) {
        Utils.showSnackBarWarning(message: 'Vui lòng nhập hạn sử dụng');
        return;
      } else if (selectedStampType.value.isEmpty) {
        Utils.showSnackBarWarning(message: 'Vui lòng nhập mẫu tem');
        return;
      }
      print(requestStamp.toJson());
      UtilWidget.showLoading();
      await repository.createStamp(
        (success) {
          UtilWidget.hideDialog();
          Get.back(result: 'ok');
          Utils.showSnackBarSuccess();
        },
        (errorMessage) {
          UtilWidget.hideDialog();
          Utils.showSnackBarError();
        },
        item: requestStamp,
      );
    }
  }
}
