import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sigap/src/features/daily-ops/data/models/index.dart';
import 'package:sigap/src/utils/validators/validation.dart';

class UnitInfoController extends GetxController {
  // Singleton instance
  static UnitInfoController get instance => Get.find();

  // Static form key
  // final GlobalKey<FormState> formKey = TGlobalFormKey.unitInfo();
  // Manual validation as fallback
  final RxBool isFormValid = RxBool(true);
  // Controllers
  final positionController = TextEditingController();
  final unitIdController = TextEditingController();

  // Available units for officer role
  final RxList<UnitModel> availableUnits = <UnitModel>[].obs;

  // Error states
  final RxString positionError = ''.obs;
  final RxString unitIdError = ''.obs;

  bool validate(GlobalKey<FormState> formKey) {
    clearErrors();

    if (formKey.currentState?.validate() ?? false) {
      return true;
    }



    final positionValidation = TValidators.validateUserInput(
      'Position',
      positionController.text,
      100,
    );
    if (positionValidation != null) {
      positionError.value = positionValidation;
      isFormValid.value = false;
    }

    if (unitIdController.text.isEmpty) {
      unitIdError.value = 'Please select a unit';
      isFormValid.value = false;
    }

    return isFormValid.value;
  }

  void clearErrors() {
    positionError.value = '';
    unitIdError.value = '';
  }

  @override
  void onClose() {
    positionController.dispose();
    unitIdController.dispose();
    super.onClose();
  }
}
