import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:real_estate_mobile/core/network/api_client.dart';
import 'package:real_estate_mobile/core/network/api_exceptions.dart';
import 'package:real_estate_mobile/core/services/push_notification_service.dart';
import 'package:real_estate_mobile/core/storage/secure_storage.dart';
import 'package:real_estate_mobile/features/auth/data/auth_repository.dart';
import 'package:real_estate_mobile/features/auth/data/models/register_request.dart';
import 'package:real_estate_mobile/features/auth/data/models/user_model.dart';
import 'package:real_estate_mobile/features/messaging/data/socket_service.dart';

// Auth state
enum AuthStatus { initial, loading, authenticated, error }

class AuthState {
  final AuthStatus status;
  final UserModel? user;
  final String? errorMessage;
  final List<FieldError> fieldErrors;
  final String registeredEmail;
  final bool requiresTwoFactor;
  final String? tempToken;
  final String? twoFactorEmail;

  const AuthState({
    this.status = AuthStatus.initial,
    this.user,
    this.errorMessage,
    this.fieldErrors = const [],
    this.registeredEmail = '',
    this.requiresTwoFactor = false,
    this.tempToken,
    this.twoFactorEmail,
  });

  AuthState copyWith({
    AuthStatus? status,
    UserModel? user,
    String? errorMessage,
    List<FieldError>? fieldErrors,
    String? registeredEmail,
    bool? requiresTwoFactor,
    String? tempToken,
    String? twoFactorEmail,
  }) {
    return AuthState(
      status: status ?? this.status,
      user: user ?? this.user,
      errorMessage: errorMessage,
      fieldErrors: fieldErrors ?? this.fieldErrors,
      registeredEmail: registeredEmail ?? this.registeredEmail,
      requiresTwoFactor: requiresTwoFactor ?? this.requiresTwoFactor,
      tempToken: tempToken ?? this.tempToken,
      twoFactorEmail: twoFactorEmail ?? this.twoFactorEmail,
    );
  }

  String? getFieldError(String fieldName) {
    final match = fieldErrors.where((e) => e.field == fieldName);
    if (match.isEmpty) return null;
    return match.first.errors.isNotEmpty ? match.first.errors.first : null;
  }
}

// Auth notifier
class AuthNotifier extends StateNotifier<AuthState> {
  final AuthRepository _repository;

  AuthNotifier(this._repository)
      : super(const AuthState(status: AuthStatus.loading)) {
    // Wire up force logout callback so API client can reset auth state
    // when token refresh fails
    ApiClient.onForceLogout = () {
      SocketService().disconnect();
      state = const AuthState();
    };
    checkAuthStatus();
  }

  Future<void> checkAuthStatus() async {
    state = state.copyWith(status: AuthStatus.loading);

    final token = await SecureStorage.getAccessToken();
    if (token == null) {
      state = state.copyWith(status: AuthStatus.initial);
      return;
    }

    try {
      final user = await _repository.getMe();
      state = state.copyWith(
        status: AuthStatus.authenticated,
        user: user,
      );
      // Connect socket for real-time updates (matching web's PresenceProvider)
      _connectSocket();
      // Register for push notifications after auth confirmed
      _initPushNotifications();
    } catch (_) {
      // Token is invalid/expired — clear and show login
      await SecureStorage.clearTokens();
      state = state.copyWith(status: AuthStatus.initial);
    }
  }

  Future<void> logout() async {
    // Disconnect socket immediately
    SocketService().disconnect();
    // Attempt FCM unregister and API logout (best-effort, don't block)
    try {
      await PushNotificationService().unregister();
    } catch (_) {}
    try {
      await _repository.logout();
    } catch (_) {}
    state = const AuthState();
  }

  Future<void> login({
    required String email,
    required String password,
  }) async {
    state = state.copyWith(
      status: AuthStatus.loading,
      errorMessage: null,
      fieldErrors: [],
    );

    try {
      final result = await _repository.login(
        email: email,
        password: password,
      );

      if (result['requiresTwoFactor'] == true) {
        state = state.copyWith(
          status: AuthStatus.initial,
          requiresTwoFactor: true,
          tempToken: result['tempToken'] as String?,
          twoFactorEmail: email,
        );
        return;
      }

      state = state.copyWith(
        status: AuthStatus.authenticated,
        user: result['user'] as UserModel,
      );
      _connectSocket();
      _initPushNotifications();
    } on ApiException catch (e) {
      state = state.copyWith(
        status: AuthStatus.error,
        errorMessage: e.fieldErrors.isNotEmpty
            ? 'Please fix the errors below'
            : e.message,
        fieldErrors: e.fieldErrors,
      );
    } catch (e) {
      state = state.copyWith(
        status: AuthStatus.error,
        errorMessage: 'An unexpected error occurred',
      );
    }
  }

  Future<void> register({
    required String name,
    required String email,
    required String password,
    required String role,
  }) async {
    state = state.copyWith(
      status: AuthStatus.loading,
      errorMessage: null,
      fieldErrors: [],
    );

    // Split name into firstName and lastName
    final nameParts = name.trim().split(RegExp(r'\s+'));
    final firstName = nameParts.first;
    final lastName = nameParts.length > 1 ? nameParts.sublist(1).join(' ') : null;

    try {
      final user = await _repository.register(
        RegisterRequest(
          email: email,
          password: password,
          role: role,
          firstName: firstName,
          lastName: lastName,
        ),
      );

      state = state.copyWith(
        status: AuthStatus.authenticated,
        user: user,
        registeredEmail: email,
      );
      _connectSocket();
      _initPushNotifications();
    } on ApiException catch (e) {
      state = state.copyWith(
        status: AuthStatus.error,
        errorMessage: e.fieldErrors.isNotEmpty
            ? 'Please fix the errors below'
            : e.message,
        fieldErrors: e.fieldErrors,
      );
    } catch (e) {
      state = state.copyWith(
        status: AuthStatus.error,
        errorMessage: 'An unexpected error occurred',
      );
    }
  }

  Future<void> verifyTwoFactor(String token) async {
    final tempToken = state.tempToken;
    if (tempToken == null) {
      state = state.copyWith(
        errorMessage: 'Session expired. Please login again.',
      );
      return;
    }

    state = state.copyWith(
      status: AuthStatus.loading,
      errorMessage: null,
    );

    try {
      final authResponse = await _repository.verifyTwoFactor(
        tempToken: tempToken,
        token: token,
      );
      state = AuthState(
        status: AuthStatus.authenticated,
        user: authResponse.user,
      );
      _connectSocket();
      _initPushNotifications();
    } on ApiException catch (e) {
      // Preserve tempToken and requiresTwoFactor so user can retry
      state = state.copyWith(
        status: AuthStatus.initial,
        requiresTwoFactor: true,
        errorMessage: e.message,
      );
    } catch (e) {
      state = state.copyWith(
        status: AuthStatus.initial,
        requiresTwoFactor: true,
        errorMessage: 'Verification failed. Please try again.',
      );
    }
  }

  Future<void> verifyBackupCode(String backupCode) async {
    final tempToken = state.tempToken;
    if (tempToken == null) {
      state = state.copyWith(
        errorMessage: 'Session expired. Please login again.',
      );
      return;
    }

    state = state.copyWith(
      status: AuthStatus.loading,
      errorMessage: null,
    );

    try {
      final authResponse = await _repository.verifyBackupCode(
        tempToken: tempToken,
        backupCode: backupCode,
      );
      state = AuthState(
        status: AuthStatus.authenticated,
        user: authResponse.user,
      );
      _connectSocket();
      _initPushNotifications();
    } on ApiException catch (e) {
      state = state.copyWith(
        status: AuthStatus.initial,
        requiresTwoFactor: true,
        errorMessage: e.message,
      );
    } catch (e) {
      state = state.copyWith(
        status: AuthStatus.initial,
        requiresTwoFactor: true,
        errorMessage: 'Verification failed. Please try again.',
      );
    }
  }

  void clearTwoFactor() {
    state = const AuthState();
  }

  void _connectSocket() {
    SocketService().connect();
  }

  void _initPushNotifications() {
    final push = PushNotificationService();
    push.initialize().then((_) => push.registerAfterLogin());
  }

  void reset() {
    state = const AuthState();
  }
}

// Providers
final authRepositoryProvider = Provider<AuthRepository>((ref) {
  return AuthRepository();
});

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