import 'package:get/get.dart';

import '../models/filament_model.dart';
import '../services/appwrite_service.dart';
import '../widgets/add_filament_dialog.dart';

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

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

  @override
  void onReady() {}

  @override
  void onClose() {}

  void _loadFilaments() async {
    isloading.value = true;
    filaments.clear();
    try {
      final loggedIn = await appwriteService.login();
      if (!loggedIn) {
        print('Login fehlgeschlagen – Daten können nicht geladen werden.');
        return;
      }
      final documents = await appwriteService.getFilamentDocuments();
      if (documents.isEmpty) {
        print('Keine Filamente gefunden.');
      } else {
        print('${documents.length} Filamente geladen.');
        filaments.assignAll(
          documents.map(
            (doc) => FilamentModel.fromJson({'\$id': doc.$id, ...doc.data}),
          ),
        );
      }
    } catch (e, st) {
      print('Fehler beim Laden der Filamente: $e\n$st');
    } finally {
      isloading.value = false;
      update();
    }
  }

  void addFilament(FilamentModel entry) {
    filaments.add(entry);
    appwriteService.createFilamentDocument(
      FilamentModel.toMapForAppwrite(entry),
    );
    update();
  }

  void editFilament(FilamentModel updated) {
    final idx = filaments.indexWhere((f) => f.documentId == updated.documentId);
    if (idx != -1) {
      filaments[idx] = updated;
      appwriteService.updateFilamentDocument(
        updated.documentId,
        FilamentModel.toMapForAppwrite(updated),
      );
      update();
    }
  }

  void deleteFilament(FilamentModel filament) {
    filaments.remove(filament);
    appwriteService.deleteFilamentDocument(filament.documentId);
    update();
  }

  /// Nur lokal löschen (Appwrite wurde bereits vom DetailController aufgerufen).
  void deleteFilamentLocal(FilamentModel filament) {
    filaments.removeWhere((f) => f.documentId == filament.documentId);
    update();
  }

  Future<void> openAddDialog() async {
    final entry = await AddFilamentDialog.show();
    if (entry != null) addFilament(entry);
  }

  Future<void> openEditDialog(FilamentModel existing) async {
    final updated = await AddFilamentDialog.showEdit(entry: existing);
    if (updated != null) editFilament(updated);
  }
}
