import 'dart:async';
import 'dart:io';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../config/app_config.dart';

/// Tracks network connectivity by periodically pinging the API gateway.
/// More reliable than connectivity_plus (which only checks if Wi-Fi/data is on,
/// not if the server is actually reachable).
class ConnectivityNotifier extends StateNotifier<ConnectivityState> {
  final String _apiBaseUrl;
  Timer? _timer;

  ConnectivityNotifier(this._apiBaseUrl) : super(const ConnectivityState()) {
    check();
    _timer = Timer.periodic(const Duration(seconds: 30), (_) => check());
  }

  Future<void> check() async {
    try {
      final uri = Uri.parse(_apiBaseUrl);
      final socket = await Socket.connect(
        uri.host,
        uri.port,
        timeout: const Duration(seconds: 5),
      );
      socket.destroy();
      if (mounted) {
        state = const ConnectivityState(isOnline: true);
      }
    } catch (_) {
      if (mounted) {
        state = ConnectivityState(
          isOnline: false,
          lastOfflineAt: DateTime.now(),
        );
      }
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }
}

class ConnectivityState {
  final bool isOnline;
  final DateTime? lastOfflineAt;

  const ConnectivityState({
    this.isOnline = true,
    this.lastOfflineAt,
  });
}

final connectivityProvider =
    StateNotifierProvider<ConnectivityNotifier, ConnectivityState>((ref) {
  final config = ref.watch(appConfigProvider);
  return ConnectivityNotifier(config.apiBaseUrl);
});

final isOnlineProvider = Provider<bool>((ref) {
  return ref.watch(connectivityProvider).isOnline;
});
