import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../constants/app_constants.dart';
import '../models/auth_models.dart';
import '../services/auth_service.dart';
import '../storage/token_storage.dart';

enum AuthStatus { unknown, authenticated, unauthenticated }

class AuthState {
  final AuthStatus status;
  final String? userType;
  final Employee? employee;
  final Renter? renter;

  const AuthState({
    required this.status,
    this.userType,
    this.employee,
    this.renter,
  });

  AuthState copyWith({
    AuthStatus? status,
    String? userType,
    Employee? employee,
    Renter? renter,
  }) =>
      AuthState(
        status: status ?? this.status,
        userType: userType ?? this.userType,
        employee: employee ?? this.employee,
        renter: renter ?? this.renter,
      );
}

class AuthNotifier extends StateNotifier<AuthState> {
  final AuthService _service;

  AuthNotifier(this._service)
      : super(const AuthState(status: AuthStatus.unknown));

  Future<void> init() async {
    final token = await TokenStorage.getToken();
    final userType = await TokenStorage.getUserType();
    if (token == null || userType == null) {
      state = const AuthState(status: AuthStatus.unauthenticated);
      return;
    }
    try {
      if (userType == AppConstants.userTypeEmployee) {
        final employee = await _service.getMe();
        state = AuthState(
          status: AuthStatus.authenticated,
          userType: userType,
          employee: employee,
        );
      } else {
        final renter = await _service.getRenterMe();
        state = AuthState(
          status: AuthStatus.authenticated,
          userType: userType,
          renter: renter,
        );
      }
    } catch (_) {
      await TokenStorage.clear();
      state = const AuthState(status: AuthStatus.unauthenticated);
    }
  }

  Future<void> loginEmployee(String email, String password) async {
    final result = await _service.loginEmployee(email: email, password: password);
    await TokenStorage.saveToken(result.token);
    await TokenStorage.saveUserType(AppConstants.userTypeEmployee);
    state = AuthState(
      status: AuthStatus.authenticated,
      userType: AppConstants.userTypeEmployee,
      employee: result.employee,
    );
  }

  Future<void> logout() async {
    await _service.logout();
    state = const AuthState(status: AuthStatus.unauthenticated);
  }
}

final authServiceProvider = Provider((_) => AuthService());

final authProvider = StateNotifierProvider<AuthNotifier, AuthState>((ref) {
  return AuthNotifier(ref.read(authServiceProvider));
});
