import 'package:flutter/material.dart';
import '../models/user_model.dart';
import '../services/service_locator.dart';
import '../services/api/api_client.dart';

enum LoadStatus { idle, loading, success, error }

class UserProvider extends ChangeNotifier {
  List<UserModel> _users = [];
  LoadStatus _status = LoadStatus.idle;
  String? _error;

  List<UserModel> get users => List.unmodifiable(_users);
  LoadStatus get status => _status;
  String? get error => _error;
  bool get isLoading => _status == LoadStatus.loading;

  int get totalCount => _users.length;
  int get activeCount => _users.where((u) => u.isActive).length;

  Future<void> loadUsers() async {
    _status = LoadStatus.loading;
    _error = null;
    notifyListeners();

    try {
      _users = await ServiceLocator().users.getUsers();
      _status = LoadStatus.success;
    } on ApiException catch (e) {
      _error = e.message;
      _status = LoadStatus.error;
    } catch (e) {
      _error = 'خطا در دریافت کاربران';
      _status = LoadStatus.error;
    }
    notifyListeners();
  }

  /// Returns the new user and its generated secret.
  Future<({UserModel user, String secret})?> createUser(
    String username, {
    String? phoneNumber,
  }) async {
    _error = null;
    try {
      final result = await ServiceLocator().users.createUser(
            username,
            phoneNumber: phoneNumber,
          );
      _users = [..._users, result.user];
      notifyListeners();
      return result;
    } on ApiException catch (e) {
      _error = e.message;
      notifyListeners();
      return null;
    } catch (e) {
      _error = 'خطا در ایجاد کاربر';
      notifyListeners();
      return null;
    }
  }

  /// Returns the new secret string, or null on failure.
  Future<String?> resetSecret(String userId) async {
    _error = null;
    try {
      final secret = await ServiceLocator().users.resetSecret(userId);
      return secret;
    } on ApiException catch (e) {
      _error = e.message;
      notifyListeners();
      return null;
    } catch (e) {
      _error = 'خطا در ریست رمز';
      notifyListeners();
      return null;
    }
  }

  Future<bool> logoutUser(String userId) async {
    _error = null;
    try {
      await ServiceLocator().users.logoutUser(userId);
      return true;
    } on ApiException catch (e) {
      _error = e.message;
      notifyListeners();
      return false;
    } catch (e) {
      _error = 'خطا در خروج کاربر';
      notifyListeners();
      return false;
    }
  }

  void clearError() {
    _error = null;
    notifyListeners();
  }
}
