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';

class CompaniesManagementController extends GetxController {
  final Dio _dio = DioClient().client;

  var isLoading = true.obs;
  var companies = <Map<String, dynamic>>[].obs;

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

  Future<void> fetchCompanies() async {
    try {
      isLoading.value = true;
      final response = await _dio.get('companies');
      if (response.data['success'] == true) {
        companies.value = List<Map<String, dynamic>>.from(response.data['data']);
      }
    } catch (e) {
      AppLogger.error('Failed to fetch companies', e);
      AppSnackbar.showError('خطأ', 'تعذر تحميل قائمة الشركات');
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> updateCompany(String id, Map<String, dynamic> data) async {
    try {
      data['id'] = id;
      final response = await _dio.post('companies/update', data: data);
      if (response.data['success'] == true) {
        await fetchCompanies();
        AppSnackbar.showSuccess('نجاح', 'تم تحديث بيانات الشركة');
      }
    } catch (e) {
      AppLogger.error('Failed to update company', e);
      AppSnackbar.showError('خطأ', 'تعذر تحديث الشركة');
    }
  }

  Future<void> deleteCompany(String id) async {
    try {
      final response = await _dio.post('companies/delete', data: {'id': id});
      if (response.data['success'] == true) {
        companies.removeWhere((c) => c['id'] == id);
        AppSnackbar.showSuccess('نجاح', 'تم حذف الشركة بنجاح');
      }
    } catch (e) {
      AppLogger.error('Failed to delete company', e);
      AppSnackbar.showError('خطأ', 'تعذر حذف الشركة');
    }
  }

  Future<void> connectJoFotara(String id, String clientId, String secretKey, String sequence) async {
    try {
      isLoading.value = true;
      final response = await _dio.post('companies/connect_jofotara', data: {
        'id': id,
        'client_id': clientId,
        'secret_key': secretKey,
        'income_source_sequence': sequence,
      });
      if (response.data['success'] == true) {
        await fetchCompanies();
        AppSnackbar.showSuccess('نجاح', 'تم ربط الشركة بجوفوترا بنجاح');
      } else {
        AppSnackbar.showError('خطأ', response.data['message'] ?? 'فشل الربط');
      }
    } catch (e) {
      AppLogger.error('Failed to connect jofotara', e);
      AppSnackbar.showError('خطأ', 'تعذر ربط جوفوترا');
    } finally {
      isLoading.value = false;
    }
  }
}
