import 'package:flutter/material.dart';
import 'package:phone_login/services/auth_service.dart';
import 'package:phone_login/shared/models/user_model.dart';
import 'package:firebase_auth/firebase_auth.dart' as firebase;

class AuthState extends ChangeNotifier {
  final AuthService _authService;

  AuthState(this._authService) {
    _authService.user.listen(_onUserChanged);
  }

  bool _isLoading = false;
  bool get isLoading => _isLoading;

  bool _isLoggedIn = false;
  bool get isLoggedIn => _isLoggedIn;

  String? _errorMessage;
  String? get errorMessage => _errorMessage;

  UserModel? _currentUser;
  UserModel? get currentUser => _currentUser;

  void _onUserChanged(firebase.User? user) {
    if (user != null) {
      _isLoggedIn = true;
      _currentUser = UserModel.fromFirebaseUser(user);
    } else {
      _isLoggedIn = false;
      _currentUser = null;
    }
    _isLoading = false;
    notifyListeners();
  }

  Future<void> signInWithPhoneNumber(String phoneNumber) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      await _authService.signInWithPhoneNumber(phoneNumber);
    } on Exception catch (e) {
      _errorMessage = e.toString();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> verifyOTP(String verificationId, String otp) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      await _authService.verifyOTP(verificationId, otp);
    } on Exception catch (e) {
      _errorMessage = e.toString();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> logout() async {
    _isLoading = true;
    notifyListeners();

    try {
      await _authService.signOut();
      _isLoggedIn = false;
      _currentUser = null;
    } on Exception catch (e) {
      _errorMessage = e.toString();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }
}
