import 'dart:async';

import 'package:pocketbase/pocketbase.dart';

import 'package:listenmeister/models/models.dart';

class ApiService {
  final PocketBase pb;

  ApiService(this.pb);

  String? get userId => pb.authStore.record?.id;

  Future<void> login(String email, String password) async {
    await pb.collection('users').authWithPassword(email, password);
  }

  Future<void> register(String email, String password) async {
    await pb
        .collection('users')
        .create(
          body: {
            'email': email,
            'password': password,
            'passwordConfirm': password,
            'emailVisibility': true,
          },
        );
    await login(email, password);
  }

  void logout() {
    pb.authStore.clear();
  }

  Stream<void> watchLists() {
    if (userId == null) return Stream.value(null);

    late final StreamController<void> controller;
    Future<void> Function()? unsubscribe;

    controller = StreamController<void>(
      onListen: () async {
        unsubscribe = await pb.collection('lists').subscribe('*', (e) {
          if (!controller.isClosed) {
            controller.add(null);
          }
        }, filter: 'owner = "$userId" || members ?~ "$userId"');
      },
      onCancel: () {
        unsubscribe?.call();
      },
    );

    return controller.stream;
  }

  Future<List<Liste>> getLists() async {
    if (userId == null) return [];
    final List<RecordModel> res = await pb
        .collection('lists')
        .getFullList(filter: 'owner = "$userId" || members ?~ "$userId"');
    return res.map((r) => Liste.fromJson(r.toJson())).toList();
  }

  Future<Liste> createList(String title) async {
    if (userId == null) throw Exception('Nicht eingeloggt');
    final RecordModel rec = await pb
        .collection('lists')
        .create(body: {'title': title, 'owner': userId});
    return Liste.fromJson(rec.toJson());
  }

  Future<void> updateList(
    String listId, {
    String? title,
    List<String>? members,
  }) async {
    if (title == null && members == null) return;
    final body = <String, dynamic>{};
    if (title != null) {
      body['title'] = title;
    }
    if (members != null) {
      body['members'] = members;
    }
    await pb.collection('lists').update(listId, body: body);
  }

  Future<void> deleteList(String listId) async {
    await pb.collection('lists').delete(listId);
  }

  Stream<void> watchItems(String listId) {
    late final StreamController<void> controller;
    Future<void> Function()? unsubscribe;

    controller = StreamController<void>(
      onListen: () async {
        unsubscribe = await pb.collection('items').subscribe('*', (e) {
          if (!controller.isClosed) {
            controller.add(null);
          }
        }, filter: 'list = "$listId"');
      },
      onCancel: () {
        unsubscribe?.call();
      },
    );

    return controller.stream;
  }

  Future<List<Item>> getItems(String listId) async {
    final List<RecordModel> res = await pb
        .collection('items')
        .getFullList(filter: 'list = "$listId"', sort: 'position');
    return res.map((r) => Item.fromJson(r.toJson())).toList();
  }

  Future<Item> createItem(String listId, String name, int position) async {
    final RecordModel rec = await pb
        .collection('items')
        .create(
          body: {
            'list': listId,
            'name': name,
            'position': position,
            'checked': false,
          },
        );
    return Item.fromJson(rec.toJson());
  }

  Future<void> deleteItem(String itemId) async {
    await pb.collection('items').delete(itemId);
  }

  Future<void> updateItem(String itemId, {bool? checked, String? name}) async {
    if (checked == null && name == null) return;
    final Map<String, dynamic> body = <String, dynamic>{};
    if (checked != null) {
      body['checked'] = checked;
    }
    if (name != null) {
      body['name'] = name;
    }
    await pb.collection('items').update(itemId, body: body);
  }

  Future<RecordModel?> findUserByEmail(String email) async {
    try {
      return await pb.collection('users').getFirstListItem('email = "$email"');
    } catch (e) {
      return null;
    }
  }

  Future<List<RecordModel>> getUsersByIds(List<String> ids) async {
    if (ids.isEmpty) return [];
    final String filter = ids.map((id) => 'id = "$id"').join(' || ');
    return await pb.collection('users').getFullList(filter: filter);
  }
}
