import 'package:flutter/foundation.dart'; import '../models/closed_tab.dart'; import '../services/bar_tab_service.dart'; class HistoryViewModel extends ChangeNotifier { final BarTabService barTabService; HistoryViewModel({required this.barTabService}); static const int _pageSize = 20; List _closedTabs = []; List _customerNames = []; String? _selectedCustomer; int _offset = 0; int _totalCount = 0; bool _isLoading = false; bool _hasLoaded = false; bool _isLoadingMore = false; String? _errorMessage; String _searchQuery = ''; List get closedTabs { if (_searchQuery.isEmpty) return _closedTabs; return _closedTabs .where( (tab) => tab.customerName.toLowerCase().contains( _searchQuery.toLowerCase(), ), ) .toList(); } List get customerNames => _customerNames; String? get selectedCustomer => _selectedCustomer; bool get isLoading => _isLoading; bool get hasLoaded => _hasLoaded; bool get isLoadingMore => _isLoadingMore; bool get hasMore => _closedTabs.length < _totalCount; String? get errorMessage => _errorMessage; Future ensureLoaded() async { if (_hasLoaded || _isLoading) return; await load(); } Future load() async { if (_isLoading) return; _isLoading = true; _errorMessage = null; notifyListeners(); try { final results = await Future.wait([ _fetchPage(offset: 0), barTabService.getClosedTabCount( customerName: _selectedCustomer, ), barTabService.getDistinctCustomerNames(), ]); _closedTabs = results[0] as List; _totalCount = results[1] as int; _customerNames = results[2] as List; _offset = _closedTabs.length; } catch (e) { debugPrint('HistoryViewModel: load error: $e'); _errorMessage = 'Could not load tab history.'; } finally { _hasLoaded = true; _isLoading = false; notifyListeners(); } } Future loadMore() async { if (_isLoadingMore || !hasMore) return; _isLoadingMore = true; notifyListeners(); try { final more = await _fetchPage(offset: _offset); _closedTabs = [..._closedTabs, ...more]; _offset = _closedTabs.length; } catch (e) { debugPrint('HistoryViewModel: loadMore error: $e'); _errorMessage = 'Could not load more tabs.'; } finally { _isLoadingMore = false; notifyListeners(); } } Future> _fetchPage({required int offset}) { return barTabService.getClosedTabsPaginated( limit: _pageSize, offset: offset, customerName: _selectedCustomer, ); } void search(String query) { _searchQuery = query; notifyListeners(); } Future filterByCustomer(String? customerName) async { _selectedCustomer = customerName; _searchQuery = ''; _offset = 0; _closedTabs = []; await load(); } }