
import 'package:pshared/data/mapper/recipient/recipient.dart';
import 'package:pshared/models/recipient/filter.dart';
import 'package:pshared/models/recipient/recipient.dart';
import 'package:pshared/models/recipient/status.dart';
import 'package:pshared/models/recipient/type.dart';
import 'package:pshared/provider/organizations.dart';
import 'package:pshared/provider/template.dart';
import 'package:pshared/service/recipient/service.dart';


class RecipientsProvider extends GenericProvider<Recipient> {
  late OrganizationsProvider _organizations;

  RecipientFilter _selectedFilter = RecipientFilter.all;
  String _query = '';
  String? _previousRecipientRef;

  RecipientFilter get selectedFilter => _selectedFilter;
  String get query => _query;

  List<Recipient> get recipients => List<Recipient>.unmodifiable(items.toList()..sort((a, b) => a.storable.createdAt.compareTo(b.storable.createdAt))); 

  RecipientsProvider() : super(service: RecipientService.basicService);

  Recipient? get previousRecipient => _previousRecipientRef == null
      ? null
      : getItemByRef(_previousRecipientRef!);

  List<Recipient> get filteredRecipients {
    List<Recipient> filtered = recipients.where((r) {
      switch (_selectedFilter) {
        case RecipientFilter.ready:
          return r.status == RecipientStatus.ready;
        case RecipientFilter.registered:
          return r.status == RecipientStatus.registered;
        case RecipientFilter.notRegistered:
          return r.status == RecipientStatus.notRegistered;
        case RecipientFilter.all:
          return true;
      }
    }).toList();

    if (_query.isNotEmpty) {
      filtered = filtered.where((r) => r.matchesQuery(_query)).toList();
    }

    return filtered;
  }

  void setFilter(RecipientFilter filter) {
    _selectedFilter = filter;
    notifyListeners();
  }

  void setQuery(String query) {
    _query = query.trim().toLowerCase();
    notifyListeners();
  }

  @override
  bool setCurrentObject(String? objectRef) {
    final currentRef = currentObject?.id;
    final didUpdate = super.setCurrentObject(objectRef);

    if (didUpdate && currentRef != null && currentRef != objectRef) {
      _previousRecipientRef = currentRef;
    }

    return didUpdate;
  }

  void restorePreviousRecipient() {
    if (_previousRecipientRef != null) {
      setCurrentObject(_previousRecipientRef);
    }
  }

  Future<Recipient> create({
    required String name,
    required String email,
  }) async => createObject(
    _organizations.current.id,
    newRecipient(
      organizationRef: _organizations.current.id, 
      email: email, 
      name: name, 
      status: RecipientStatus.ready, 
      type: RecipientType.internal,
    ).toDTO().toJson(),
  );

  void updateProviders(OrganizationsProvider organizations) {
    _organizations = organizations;
    if (_organizations.isOrganizationSet) {
      load(_organizations.current.id, _organizations.current.id);
    }
  }
}
