import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../core/auth_storage.dart';
import '../core/team_selection_storage.dart';
import '../shared/models/user.dart';

class AuthState {
  const AuthState({
    this.user,
    this.accessToken,
    this.refreshToken,
    this.loading = false,
    this.error,
  });

  final User? user;
  final String? accessToken;
  final String? refreshToken;
  final bool loading;
  final String? error;

  bool get isAuthenticated =>
      accessToken != null && accessToken!.isNotEmpty && user != null;

  AuthState copyWith({
    User? user,
    String? accessToken,
    String? refreshToken,
    bool? loading,
    String? error,
    bool clearError = false,
  }) {
    return AuthState(
      user: user ?? this.user,
      accessToken: accessToken ?? this.accessToken,
      refreshToken: refreshToken ?? this.refreshToken,
      loading: loading ?? this.loading,
      error: clearError ? null : (error ?? this.error),
    );
  }
}

class AuthNotifier extends StateNotifier<AuthState> {
  AuthNotifier() : super(const AuthState());

  void setSession({
    required User user,
    required String accessToken,
    required String refreshToken,
  }) {
    state = AuthState(
      user: user,
      accessToken: accessToken,
      refreshToken: refreshToken,
      loading: false,
    );
    AuthStorage.save(
      user: user,
      accessToken: accessToken,
      refreshToken: refreshToken,
    );
  }

  Future<void> restoreSession() async {
    final stored = await AuthStorage.load();
    if (stored == null) return;
    state = AuthState(
      user: stored.user,
      accessToken: stored.accessToken,
      refreshToken: stored.refreshToken,
      loading: false,
    );
  }

  void setLoading(bool loading) {
    state = state.copyWith(loading: loading, clearError: true);
  }

  void setError(String message) {
    state = state.copyWith(loading: false, error: message);
  }

  void logout() {
    state = const AuthState();
    AuthStorage.clear();
    TeamSelectionStorage.clear();
  }
}

final authProvider = StateNotifierProvider<AuthNotifier, AuthState>(
  (ref) => AuthNotifier(),
);
