import 'package:flutter/material.dart';

import 'package:pshared/models/payment/operation.dart';
import 'package:pshared/models/payment/status.dart';

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


class OperationProvider extends ChangeNotifier {
  final OperationService _service;
  
  OperationProvider(this._service);
  
  List<OperationItem> _allOperations = [];
  List<OperationItem> _filteredOperations = [];
  DateTimeRange? _dateRange;
  final Set<String> _selectedStatuses = {};
  bool _isLoading = false;
  String? _error;
  
  // Getters
  List<OperationItem> get allOperations => _allOperations;
  List<OperationItem> get filteredOperations => _filteredOperations;
  DateTimeRange? get dateRange => _dateRange;
  Set<String> get selectedStatuses => _selectedStatuses;
  bool get isLoading => _isLoading;
  String? get error => _error;
  bool get hasFileName => _allOperations.any((op) => op.fileName != null);
  
  Future<void> loadOperations() async {
    _isLoading = true;
    _error = null;
    notifyListeners();
    
    try {
      _allOperations = await _service.fetchOperations();
      _filteredOperations = List.from(_allOperations);
      _isLoading = false;
      notifyListeners();
    } catch (e) {
      _error = e.toString();
      _isLoading = false;
      notifyListeners();
    }
  }
  
  void setDateRange(DateTimeRange? range) {
    _dateRange = range;
    notifyListeners();
  }
  
  void toggleStatus(String status) {
    if (_selectedStatuses.contains(status)) {
      _selectedStatuses.remove(status);
    } else {
      _selectedStatuses.add(status);
    }
    notifyListeners();
  }
  
  void applyFilters(BuildContext context) {
    _filteredOperations = _allOperations.where((op) {
      final statusMatch = _selectedStatuses.isEmpty || 
          _selectedStatuses.contains(op.status.localized(context));
      
      final dateMatch = _dateRange == null ||
          (op.date.isAfter(_dateRange!.start.subtract(const Duration(seconds: 1))) &&
           op.date.isBefore(_dateRange!.end.add(const Duration(seconds: 1))));
      
      return statusMatch && dateMatch;
    }).toList();
    
    notifyListeners();
  }
  
  void resetFilters() {
    _dateRange = null;
    _selectedStatuses.clear();
    _filteredOperations = List.from(_allOperations);
    notifyListeners();
  }
}
