import 'package:flutter/material.dart';

import 'package:pshared/models/invitation/invitation.dart';

import 'package:pweb/models/invitation/invitation_filter.dart';
import 'package:pweb/pages/invitations/widgets/filter/invitation_filter.dart';


class InvitationListViewModel extends ChangeNotifier {
  InvitationFilter _filter = InvitationFilter.all;
  String _query = '';

  InvitationFilter get filter => _filter;
  String get query => _query;

  void setFilter(InvitationFilter filter) {
    if (_filter == filter) return;
    _filter = filter;
    notifyListeners();
  }

  void setQuery(String query) {
    final normalized = query.trim().toLowerCase();
    if (_query == normalized) return;
    _query = normalized;
    notifyListeners();
  }

  List<Invitation> filteredInvitations(List<Invitation> invitations) {
    final showArchived = _filter == InvitationFilter.archived;
    Iterable<Invitation> filtered = invitations
        .where((inv) => showArchived ? inv.isArchived : !inv.isArchived)
        .where((inv) => invitationFilterMatches(_filter, inv));

    if (_query.isNotEmpty) {
      filtered = filtered.where((inv) {
        return inv.inviteeDisplayName.toLowerCase().contains(_query)
            || inv.content.email.toLowerCase().contains(_query);
      });
    }

    final sorted = filtered.toList()
      ..sort((a, b) => b.createdAt.compareTo(a.createdAt));
    return sorted;
  }
}
