import 'package:get/get.dart';
import 'package:terepi_seged/services/project_service.dart';

import '../../../../services/contact_service.dart';

class ContactsController extends GetxController {
  final items = <ContactWithState>[].obs;
  final isLoading = false.obs;
  final error = ''.obs;
  final search = ''.obs;
  final pendingCount = 0.obs;

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

  List<ContactWithState> get filtered {
    final q = search.value.trim().toLowerCase();
    if (q.isEmpty) return items;
    return items.where((it) {
      final c = it.contact;
      return c.name.toLowerCase().contains(q) ||
          c.phone.toLowerCase().contains(q) ||
          c.email.toLowerCase().contains(q) ||
          c.address.toLowerCase().contains(q);
    }).toList();
  }

  Future<void> load({bool silent = false}) async {
    final projectId = ProjectService.to.activeProject.value?.uuid;
    if (projectId == null) {
      error.value = 'Nincs aktív projekt.';
      isLoading.value = false;
      return;
    }
    if (!silent) isLoading.value = true;
    error.value = '';
    try {
      items.value = await ContactService.to.listMerged(projectId);
      pendingCount.value = await ContactService.to.pendingCount(projectId);
    } catch (e) {
      error.value = _friendly(e);
    } finally {
      if (!silent) isLoading.value = false;
    }
  }

  /// Feltölti a várólistát, majd újratölt (kézi "szinkron most" gomb).
  Future<void> flushNow() async {
    try {
      final n = await ContactService.to.flush();
      if (n > 0) {
        Get.snackbar('Szinkron', '$n kapcsolat feltöltve.',
            snackPosition: SnackPosition.BOTTOM);
      }
      await load();
    } catch (e) {
      Get.snackbar('Szinkron', _friendly(e),
          snackPosition: SnackPosition.BOTTOM);
    }
  }

  Future<void> delete(ContactWithState it) async {
    try {
      await ContactService.to
          .delete(id: it.contact.id, localUuid: it.localUuid);
      items.remove(it);
      final projectId = ProjectService.to.activeProject.value?.uuid;
      if (projectId != null) {
        pendingCount.value = await ContactService.to.pendingCount(projectId);
      }
    } catch (e) {
      Get.snackbar('Hiba', _friendly(e), snackPosition: SnackPosition.BOTTOM);
    }
  }

  String _friendly(Object e) {
    final s = e.toString();
    if (s.contains('permission') ||
        s.contains('policy') ||
        s.contains('row-level')) {
      return 'Nincs jogosultságod a kapcsolatok eléréséhez.';
    }
    if (s.contains('SocketException') || s.contains('Failed host')) {
      return 'Nincs hálózati kapcsolat.';
    }
    return s;
  }
}
