import 'package:flutter/foundation.dart';
import 'package:qpay/http/http.dart';
import 'package:qpay/screens/workspaces/workspace_model.dart';

/// Describes the current state of the workspace fetch operation.
enum WorkspaceStatus { idle, loading, success, error }

/// A [ChangeNotifier] that fetches and caches the list of workspaces
/// for the current user from the backend.
///
/// Usage:
/// ```dart
/// final provider = context.read<WorkspaceProvider>();
/// await provider.fetchWorkspaces(userId: '...');
/// ```
class WorkspaceProvider extends ChangeNotifier {
  final Http _http = Http();

  WorkspaceStatus _status = WorkspaceStatus.idle;
  List<WorkspaceModel> _workspaces = [];
  String? _error;

  WorkspaceStatus get status => _status;
  List<WorkspaceModel> get workspaces => _workspaces;
  String? get error => _error;
  bool get isLoading => _status == WorkspaceStatus.loading;
  bool get hasError => _status == WorkspaceStatus.error;

  /// Fetches workspaces for the given [userId].
  ///
  /// On success, [workspaces] is updated and [status] becomes
  /// [WorkspaceStatus.success].
  /// On failure, [error] is set and [status] becomes
  /// [WorkspaceStatus.error].
  Future<void> fetchWorkspaces({required String userId}) async {
    _status = WorkspaceStatus.loading;
    _error = null;
    notifyListeners();

    try {
      final response = await _http.getRaw('/workspaces?userId=$userId');

      if (response.statusCode == 200) {
        final body = response.data as Map<String, dynamic>;
        final content = body['content'] as List<dynamic>;
        _workspaces = content
            .map((e) => WorkspaceModel.fromJson(e as Map<String, dynamic>))
            .toList();
        _status = WorkspaceStatus.success;
      } else if (response.statusCode == 403) {
        _error =
            'Access denied. You do not have permission to view workspaces.';
        _status = WorkspaceStatus.error;
      } else {
        _error = 'Failed to load workspaces (status ${response.statusCode})';
        _status = WorkspaceStatus.error;
      }
    } catch (e) {
      _error = 'Network error: ${e.toString()}';
      _status = WorkspaceStatus.error;
    }

    notifyListeners();
  }

  /// Clears the current workspace list and resets to idle.
  void reset() {
    _status = WorkspaceStatus.idle;
    _workspaces = [];
    _error = null;
    notifyListeners();
  }
}
