import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:farm_tpf/presentation/screens/codes/models/activity_request.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';
import '../../../custom_widgets/widget_utils.dart';
import '../models/activity_type.dart';

part 'update_activity_state.dart';

class UpdateActivityCubit extends Cubit<UpdateActivityState> {
  UpdateActivityCubit() : super(UpdateActivityInitial());
  final repository = Repository();
  final formKey = GlobalKey<FormState>();
  var actionDate = ValueNotifier(DateTime.now());
  final descriptionCtl = TextEditingController();
  final locationCtl = TextEditingController();
  final expiredDateCtl = TextEditingController();
  var activityTypeRaws = <ActivityType>[];
  var activityTypes = ValueNotifier(<ItemDropDown>[]);
  var selectedActivityType = ValueNotifier('');
  // var existedUpdateActivity = UpdateUpdateActivity();

  void dispose() {
    descriptionCtl.dispose();
    locationCtl.dispose();
    expiredDateCtl.dispose();
  }

  Future<void> preparedData() async {
    try {
      await Future.delayed(const Duration(seconds: 0));
      emit(UpdateActivityLoading());
      activityTypeRaws = await repository.activityTypes();
      activityTypes.value = activityTypeRaws
          .map(
            (e) => ItemDropDown(key: e.id?.toString(), value: e.description),
          )
          .toList();
      emit(UpdateActivityPrepareDataSuccessful());
    } catch (e) {
      emit(UpdateActivityFailure(AppException.handleError(e)));
    }
  }

  Future<void> onSubmit(String stampCode) async {
    if (formKey.currentState!.validate()) {
      var requestActivity = ActivityRequest();

      var activity = activityTypeRaws.firstWhere(
        (e) => selectedActivityType.value == e.id?.toString(),
        orElse: () => ActivityType(),
      );

      requestActivity
        ..code = stampCode
        ..description = descriptionCtl.text
        ..location = locationCtl.text
        ..executeDate = actionDate.value.convertLocalDateTimeToStringUtcDateTime()
        ..activityTypeId = activity.id;
      print(requestActivity.toJson());
      UtilWidget.showLoading();
      await repository.updateActivity(
        (success) {
          UtilWidget.hideDialog();
          Get.back(result: 'ok');
          Utils.showSnackBarSuccess();
        },
        (errorMessage) {
          UtilWidget.hideDialog();
          Utils.showSnackBarError();
        },
        item: requestActivity,
      );
    }
  }
}
