import 'dart:convert';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';

final authStoreProvider = StateNotifierProvider<AuthStoreNotifier, AuthState>((ref) {
  return AuthStoreNotifier();
});

class AuthState {
  final String? token;
  final Map<String, dynamic>? user;
  final List<Map<String, dynamic>> participants;
  final bool isLoading;

  AuthState({
    this.token,
    this.user,
    this.participants = const [],
    this.isLoading = true,
  });

  bool get isAuthenticated => token != null;

  String? get userName => user?['name_ar'] as String?;
  String? get userPhone => user?['phone'] as String?;
  int? get academyId => user?['academy_id'] as int?;

  AuthState copyWith({
    String? token,
    Map<String, dynamic>? user,
    List<Map<String, dynamic>>? participants,
    bool? isLoading,
  }) {
    return AuthState(
      token: token ?? this.token,
      user: user ?? this.user,
      participants: participants ?? this.participants,
      isLoading: isLoading ?? this.isLoading,
    );
  }
}

class AuthStoreNotifier extends StateNotifier<AuthState> {
  AuthStoreNotifier() : super(AuthState()) {
    _loadFromStorage();
  }

  Future<void> _loadFromStorage() async {
    final prefs = await SharedPreferences.getInstance();
    final token = prefs.getString('auth_token');
    final userJson = prefs.getString('auth_user');
    final participantsJson = prefs.getString('auth_participants');

    if (token != null && userJson != null) {
      state = AuthState(
        token: token,
        user: jsonDecode(userJson),
        participants: participantsJson != null
            ? List<Map<String, dynamic>>.from(jsonDecode(participantsJson))
            : [],
        isLoading: false,
      );
    } else {
      state = AuthState(isLoading: false);
    }
  }

  Future<void> setAuth({
    required String token,
    required Map<String, dynamic> user,
    required List<dynamic> participants,
  }) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('auth_token', token);
    await prefs.setString('auth_user', jsonEncode(user));
    await prefs.setString('auth_participants', jsonEncode(participants));

    state = AuthState(
      token: token,
      user: user,
      participants: participants.cast<Map<String, dynamic>>(),
      isLoading: false,
    );
  }

  Future<void> updateParticipants(List<dynamic> participants) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('auth_participants', jsonEncode(participants));
    state = state.copyWith(participants: participants.cast<Map<String, dynamic>>());
  }

  Future<void> logout() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove('auth_token');
    await prefs.remove('auth_user');
    await prefs.remove('auth_participants');
    state = AuthState(isLoading: false);
  }
}
