import 'package:get/get.dart';
import 'package:on_field_work/helpers/services/api_service.dart';
import 'package:on_field_work/helpers/services/app_logger.dart';
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';

class BucketController extends GetxController {
  RxBool isCreating = false.obs;
  final RxString name = ''.obs;
  final RxString description = ''.obs;

  Future<void> createBucket() async {
    if (name.value.trim().isEmpty) {
      showAppSnackbar(
        title: "Missing Name",
        message: "Bucket name is required.",
        type: SnackbarType.warning,
      );
      return;
    }

    isCreating.value = true;

    try {
      logSafe("Creating bucket: ${name.value}");

      final success = await ApiService.createBucket(
        name: name.value.trim(),
        description: description.value.trim(),
      );

      if (success) {
        logSafe("Bucket created successfully");

        Get.back(result: true); // Close bottom sheet/dialog

        showAppSnackbar(
          title: "Success",
          message: "Bucket has been created successfully.",
          type: SnackbarType.success,
        );
      } else {
        logSafe("Bucket creation failed", level: LogLevel.error);
        showAppSnackbar(
          title: "Creation Failed",
          message: "Unable to create bucket. Please try again later.",
          type: SnackbarType.error,
        );
      }
    } catch (e) {
      logSafe("Error during bucket creation: $e", level: LogLevel.error);
      showAppSnackbar(
        title: "Unexpected Error",
        message: "Something went wrong. Please try again.",
        type: SnackbarType.error,
      );
    } finally {
      isCreating.value = false;
    }
  }

  void updateName(String value) {
    name.value = value;
    logSafe("Bucket name updated: ${value.trim()}");
  }

  void updateDescription(String value) {
    description.value = value;
    logSafe("Bucket description updated: ${value.trim()}");
  }
}
