import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart';
import '../../../core/network/dio_client.dart';
import '../../../core/utils/app_snackbar.dart';
import '../../../core/utils/logger.dart';
import 'tenants_management_controller.dart';

class AddTenantController extends GetxController {
  final nameController = TextEditingController();
  final emailController = TextEditingController();
  final managerNameController = TextEditingController();
  final managerEmailController = TextEditingController();
  final managerPasswordController = TextEditingController();

  var isSubmitting = false.obs;
  final Dio _dio = DioClient().client;

  @override
  void onClose() {
    nameController.dispose();
    emailController.dispose();
    managerNameController.dispose();
    managerEmailController.dispose();
    managerPasswordController.dispose();
    super.onClose();
  }

  Future<void> submit() async {
    final name = nameController.text.trim();
    final email = emailController.text.trim();
    final managerName = managerNameController.text.trim();
    final managerEmail = managerEmailController.text.trim();
    final managerPassword = managerPasswordController.text;

    if (name.isEmpty || email.isEmpty || managerName.isEmpty || managerEmail.isEmpty || managerPassword.isEmpty) {
      AppSnackbar.showWarning('تنبيه', 'الرجاء إدخال جميع البيانات المطلوبة');
      return;
    }

    try {
      isSubmitting.value = true;
      final response = await _dio.post('tenants/create', data: {
        'name': name,
        'email': email,
        'manager_name': managerName,
        'manager_email': managerEmail,
        'manager_password': managerPassword,
      });

      if (response.statusCode == 200 || response.statusCode == 201) {
        AppSnackbar.showSuccess('نجاح', 'تم إضافة المكتب المحاسبي بنجاح');
        
        // Refresh the list if it exists
        if (Get.isRegistered<TenantsManagementController>()) {
          Get.find<TenantsManagementController>().fetchTenants();
        }
        
        Get.back();
      } else {
        AppSnackbar.showError('خطأ', 'فشل إضافة المكتب المحاسبي');
      }
    } catch (e) {
      AppLogger.error('Failed to create tenant', e);
      AppSnackbar.showError('خطأ', 'تعذر إضافة المكتب المحاسبي، يرجى المحاولة لاحقاً');
    } finally {
      isSubmitting.value = false;
    }
  }
}
