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 '../../../core/storage/secure_storage.dart';
import '../../dashboard/controllers/dashboard_controller.dart';
import 'companies_management_controller.dart';

class AddCompanyController extends GetxController {
  final nameController = TextEditingController();
  final tinController = TextEditingController();
  final crnController = TextEditingController();

  var isSubmitting = false.obs;

  var isSuperAdmin = false.obs;
  var tenants = <Map<String, dynamic>>[].obs;
  var selectedTenantId = RxnString();
  var isLoadingTenants = false.obs;

  final Dio _dio = DioClient().client;
  final SecureStorage _storage = SecureStorage();

  @override
  void onInit() {
    super.onInit();
    _checkRoleAndFetchTenants();
  }

  Future<void> _checkRoleAndFetchTenants() async {
    String role = '';
    
    // 1. Try to get from DashboardController first
    if (Get.isRegistered<DashboardController>()) {
      role = Get.find<DashboardController>().userRole.value;
    }
    
    // 2. Fallback to SecureStorage
    if (role.isEmpty) {
      role = await _storage.read('user_role') ?? '';
    }

    if (role == 'super_admin') {
      isSuperAdmin.value = true;
      _fetchTenants();
    }
  }

  Future<void> _fetchTenants() async {
    try {
      isLoadingTenants.value = true;
      final response = await _dio.get('tenants');
      if (response.data['success'] == true) {
        tenants.value = List<Map<String, dynamic>>.from(response.data['data']);
        if (tenants.isNotEmpty) {
          selectedTenantId.value = tenants.first['id'];
        }
      }
    } catch (e) {
      AppLogger.error('Failed to fetch tenants for company creation', e);
    } finally {
      isLoadingTenants.value = false;
    }
  }

  @override
  void onClose() {
    nameController.dispose();
    tinController.dispose();
    crnController.dispose();
    super.onClose();
  }

  Future<void> submit() async {
    final name = nameController.text.trim();
    final tin = tinController.text.trim();

    if (name.isEmpty || tin.isEmpty) {
      AppSnackbar.showError('خطأ', 'الرجاء إدخال اسم الشركة والرقم الضريبي');
      return;
    }

    if (isSuperAdmin.value && selectedTenantId.value == null) {
      AppSnackbar.showWarning(
          'تنبيه', 'الرجاء اختيار المكتب المحاسبي التابع له هذه الشركة');
      return;
    }

    try {
      isSubmitting.value = true;

      final data = {
        'name': name,
        'tax_identification_number': tin,
        'commercial_registration_number': crnController.text.trim(),
      };

      if (isSuperAdmin.value) {
        data['tenant_id'] = selectedTenantId.value!;
      }

      final response = await _dio.post('companies/create', data: data);

      if (response.statusCode == 200 || response.statusCode == 201) {
        AppSnackbar.showSuccess('نجاح', 'تمت إضافة الشركة بنجاح');

        // Refresh list if controller exists
        if (Get.isRegistered<CompaniesManagementController>()) {
          Get.find<CompaniesManagementController>().fetchCompanies();
        }

        Get.back();
      } else {
        AppSnackbar.showError('خطأ', 'فشل إضافة الشركة');
      }
    } on DioException catch (e) {
      if (e.response?.statusCode == 403) {
        AppSnackbar.showError(
            'خطأ', 'لقد وصلت للحد الأقصى المسموح به للشركات في باقتك');
      } else {
        AppSnackbar.showError(
            'خطأ', e.response?.data?['message'] ?? 'تعذر إضافة الشركة');
      }
    } catch (e) {
      AppSnackbar.showError('خطأ', 'حدث خطأ غير متوقع');
    } finally {
      isSubmitting.value = false;
    }
  }
}
