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 '../../../../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();
  var stampTypeRaws = <StampType>[];
  var stampTypes = ValueNotifier(<ItemDropDown>[]);
  var selectedStampType = ValueNotifier('');
  // var existedCreateStamp = UpdateCreateStamp();

  void dispose() {
    descriptionCtl.dispose();
    quantityCtl.dispose();
    expiredDateCtl.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();
      emit(CreateStampPrepareDataSuccessful());
    } catch (e) {
      emit(CreateStampFailure(AppException.handleError(e)));
    }
  }

  Future<void> onSubmit() async {
    if (formKey.currentState!.validate()) {
      var requestStamp = RequestStamp();
      var stamp = stampTypeRaws.firstWhere(
        (e) => selectedStampType.value == e.id?.toString(),
        orElse: () => StampType(),
      );
      var expiredDate = DateTime.now().add(Duration(days: int.tryParse(expiredDateCtl.text) ?? 0));
      requestStamp
        ..description = descriptionCtl.text
        ..quantity = int.tryParse(quantityCtl.text) ?? 0
        ..expiredDate = expiredDate.convertLocalDateTimeToStringUtcDateTime()
        ..tbExampleStampId = int.tryParse(selectedStampType.value);
      print(requestStamp.toJson());
      UtilWidget.showLoading();
      await repository.createStamp(
        (success) {
          UtilWidget.hideDialog();
          Get.back(result: 'ok');
          Utils.showSnackBarSuccess();
        },
        (errorMessage) {
          UtilWidget.hideDialog();
          Utils.showSnackBarError();
        },
        item: requestStamp,
      );
    }
  }
}
