import 'package:flutter/foundation.dart';

import 'package:pshared/models/recipient/filter.dart';
import 'package:pshared/models/recipient/recipient.dart';
import 'package:pshared/models/recipient/status.dart';

import 'package:pweb/services/recipient/recipient.dart';


class RecipientProvider extends ChangeNotifier {
  final RecipientService _service;

  RecipientProvider(this._service);

  List<Recipient> _recipients = [];
  bool _isLoading = false;
  String? _error;
  RecipientFilter _selectedFilter = RecipientFilter.all;
  String _query = '';

  Recipient? _selectedRecipient;

  List<Recipient> get recipients => _recipients;
  bool get isLoading => _isLoading;
  String? get error => _error;
  RecipientFilter get selectedFilter => _selectedFilter;
  String get query => _query;
  Recipient? get selectedRecipient => _selectedRecipient;

  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;
  }

  Future<void> loadRecipients() async {
    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      _recipients = await _service.fetchRecipients();
    } catch (e) {
      _error = e.toString();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

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

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

  void selectRecipient(Recipient? recipient) {
    _selectedRecipient = recipient;
    notifyListeners();
  }
}
