import 'package:get/get.dart';

import '../models/home_model.dart';
import '../services/appwrite_service.dart';
import '../widgets/add_weight_dialog.dart';

class HomeController extends GetxController {
  final isloading = false.obs;
  final List<WeightModel> weights = <WeightModel>[].obs;
  final appwriteService = AppwriteService();

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

  @override
  void onReady() {}

  @override
  void onClose() {}

  void _loadDataList() async {
    isloading.value = true;
    if (weights.isNotEmpty) {
      weights.clear();
    }
    final loggedIn = await appwriteService.login();
    if (!loggedIn) {
      print('Login fehlgeschlagen – Daten können nicht geladen werden.');
      isloading.value = false;
      return;
    }
    final documents = await appwriteService.getDocumentsFromCollection();
    if (documents.isEmpty) {
      print('Keine Dokumente gefunden.');
    } else {
      print('${documents.length} Einträge geladen.');
      weights.assignAll(documents.map((doc) => WeightModel.fromJson(doc.data)));
    }
    isloading.value = false;
    update();
  }

  void addWeightEntry(WeightModel entry) {
    weights.add(entry);
    var map = WeightModel.toMapForAppwrite(entry);
    appwriteService.createDocumentInCollection(map);
    update();
  }

  void editWeightEntry(WeightModel updated) {
    final idx = weights.indexWhere(
      (w) => w.documentId == updated.documentId && w.date == updated.date,
    );
    if (idx != -1) {
      weights[idx] = updated;
      var map = WeightModel.toMapForAppwrite(updated);
      appwriteService.updateDocumentInCollection(updated.documentId, map);
      update();
    }
  }

  /// Gewicht des Eintrags unmittelbar VOR [date] einer Person.
  /// Wird für die weightChange-Berechnung beim Bearbeiten genutzt.
  double getPreviousWeight(String personName, DateTime date) {
    final before = weights
        .where((w) => w.name == personName && w.date.isBefore(date))
        .toList();
    if (before.isEmpty) return 0.0;
    before.sort((a, b) => b.date.compareTo(a.date));
    return before.first.weight;
  }

  /// Gibt das zuletzt eingetragene Gewicht einer Person zurück.
  /// 0.0 wenn noch kein Eintrag existiert (wird als "erster Eintrag" behandelt).
  double getLastWeight(String personName) {
    final personEntries = weights.where((w) => w.name == personName).toList();
    if (personEntries.isEmpty) return 0.0;
    personEntries.sort((a, b) => b.date.compareTo(a.date));
    return personEntries.first.weight;
  }

  void addWeight(String personName) {}

  // ── Dialog-Logik ─────────────────────────────────────────────────────────

  Future<void> openAddDialog(String personName, String userId) async {
    final entry = await AddWeightDialog.show(
      userId: userId,
      personName: personName,
      lastWeight: getLastWeight(personName),
    );
    if (entry != null) addWeightEntry(entry);
  }

  Future<void> openEditDialog(WeightModel existing) async {
    final updated = await AddWeightDialog.showEdit(
      entry: existing,
      previousWeight: getPreviousWeight(existing.name, existing.date),
    );
    if (updated != null) editWeightEntry(updated);
  }
}
