import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:farm_tpf/presentation/screens/task/models/employee.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/task_request.dart';

part 'create_task_state.dart';

class CreateTaskCubit extends Cubit<CreateTaskState> {
  CreateTaskCubit() : super(CreateTaskInitial());
  final repository = Repository();
  final formKey = GlobalKey<FormState>();
  final titleNameCtl = TextEditingController();
  final detailCtl = TextEditingController();
  var deadline = ValueNotifier(DateTime.now());

  var employeeRaws = <Employee>[];
  var employees = ValueNotifier(<ItemDropDown>[]);
  var selectedPEmployee = ValueNotifier('');
  // var existedCreateTask = UpdateCreateTask();

  void dispose() {
    titleNameCtl.dispose();
    detailCtl.dispose();
  }

  Future<void> preparedData({required int cropId}) async {
    try {
      await Future.delayed(const Duration(seconds: 0));
      emit(CreateTaskLoading());

      employeeRaws = await repository.getEmployeesByCropId(cropId);
      employees.value = employeeRaws
          .map(
            (e) => ItemDropDown(key: e.id?.toString(), value: e.name),
          )
          .toList();
      emit(CreateTaskPrepareDataSuccessful());
    } catch (e) {
      emit(CreateTaskFailure(AppException.handleError(e)));
    }
  }

  Future<void> onSubmit(int cropId) async {
    if (formKey.currentState!.validate()) {
      if (selectedPEmployee.value.isEmpty) {
        Utils.showSnackBarWarning(message: 'Vui lòng chọn nhân viên');
        return;
      }
      if (titleNameCtl.text.trim().isEmpty) {
        Utils.showSnackBarWarning(message: 'Vui lòng nhập tiêu đề');
        return;
      } else if (detailCtl.text.trim().isEmpty) {
        Utils.showSnackBarWarning(message: 'Vui lòng nhập nội dung');
        return;
      }
      var requestTask = RequestTask();
      requestTask
        ..cropId = cropId
        ..title = titleNameCtl.text
        ..detail = detailCtl.text
        ..userAssignedId = int.tryParse(selectedPEmployee.value)
        ..deadline = deadline.value.convertLocalDateTimeToStringUtcDateTime();
      print(requestTask.toJson());
      UtilWidget.showLoading();
      await repository.createTask(
        (success) {
          UtilWidget.hideDialog();
          Get.back(result: 'ok');
          Utils.showSnackBarSuccess();
        },
        (errorMessage) {
          UtilWidget.hideDialog();
          Utils.showSnackBarError();
        },
        item: requestTask,
      );
    }
  }
}
