import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:garage/car/service/car_service.dart';
import 'package:garage/user/model/car_user.dart';
import 'package:garage/user/service/user_service.dart';
import 'package:get_it/get_it.dart';

class UserProvider extends ChangeNotifier {
  CarUser? _currentUser;
  final UserService userService = GetIt.instance<UserService>();
  final CarService carService = GetIt.instance<CarService>();

  CarUser? get currentUser => _currentUser;

  set currentUser(CarUser? value) {
    _currentUser = value;
    notifyListeners();
  }

  Future<void> updateUser() async {
    final userId = FirebaseAuth.instance.currentUser!.uid;
    _currentUser = await userService.getItemById(userId);

    notifyListeners();
  }

  void addNewCar(String carId) {
    currentUser = currentUser!.copyWithNewCar(carId);
    userService.updateItem(currentUser!);
    notifyListeners();
  }

  void removeCar(String carId, bool removePhoto) {
    carService.deleteItem(carId);
    if (removePhoto) {
      carService.deletePhoto(carId);
    }
    currentUser!.cars.remove(carId);
    userService.updateItem(currentUser!);
    notifyListeners();
  }

  void archiveCar(String carId) {
    final newUser = currentUser!.copyWithArchived(carId);
    userService.updateItem(newUser);
    currentUser = newUser;
    notifyListeners();
  }

  void setAndAddToken(CarUser carUser, String? token) {
    if (token != null && !carUser.fcmTokens.contains(token)) {
      carUser.fcmTokens.add(token);
      userService.updateItem(carUser);
    }
    _currentUser = carUser;
    notifyListeners();
  }

  void setLicenceExpiration(DateTime? date) {
    final newUser = currentUser!.copyWithLicenceDate(date);
    userService.updateItem(newUser);
    currentUser = newUser;
    notifyListeners();
  }
}
