import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

import '../networks/api_client.dart';
import 'database_service.dart';

/// Rockview leave API client with offline-first stale-while-revalidate caching.
///
/// Previously synchronized leave records are painted from the authenticated
/// local snapshot immediately, then refreshed silently in the background.
/// Sensitive writes still require authoritative server confirmation so HR
/// balances, approvals and account controls cannot silently conflict.
class LeaveService {
  static const Duration _readTimeout = Duration(seconds: 8);
  static const String _cachePrefix = 'rvu_leave_cache_v5';
  static bool _networkReachable = true;
  static DateTime? _lastSuccessfulSync;

  static bool get networkReachable => _networkReachable;
  static DateTime? get lastSuccessfulSync => _lastSuccessfulSync;

  static Uri _leaveUri([Map<String, String>? query]) =>
      Uri.parse('${ApiClient.baseUrl}/api/leave.php').replace(queryParameters: query);

  static Uri _notificationUri([Map<String, String>? query]) =>
      Uri.parse('${ApiClient.baseUrl}/api/leave_notifications.php').replace(queryParameters: query);

  static Uri _hrUri([Map<String, String>? query]) =>
      Uri.parse('${ApiClient.baseUrl}/api/leave_hr.php').replace(queryParameters: query);

  static dynamic _decode(http.Response response) {
    final body = response.body.trim();
    if (body.isEmpty) return <String, dynamic>{};
    try {
      return jsonDecode(body);
    } catch (_) {
      throw FormatException('Server returned invalid JSON: $body');
    }
  }

  static String _message(http.Response response, String fallback) {
    try {
      final decoded = _decode(response);
      if (decoded is Map) {
        final value = '${decoded['detail'] ?? decoded['message'] ?? decoded['error'] ?? ''}'.trim();
        if (value.isNotEmpty) return value;
      }
    } catch (_) {}
    return '$fallback (HTTP ${response.statusCode})';
  }

  static Future<String?> _accountScope() async {
    try {
      final dynamic user = await DatabaseService.getLocalUser();
      final email = '${user?.email ?? ''}'.trim().toLowerCase();
      if (email.isNotEmpty && email != 'null') {
        return email.replaceAll(RegExp(r'[^a-z0-9._@-]'), '_');
      }
    } catch (_) {}
    return null;
  }

  static Future<String?> _cacheKey(String name) async {
    final scope = await _accountScope();
    if (scope == null) return null;
    return '${_cachePrefix}_${scope}_$name';
  }

  static Future<void> _writeCache(String name, dynamic value) async {
    final key = await _cacheKey(name);
    if (key == null) return;
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(
        key,
        jsonEncode({
          'saved_at': DateTime.now().toIso8601String(),
          'payload': value,
        }),
      );
    } catch (_) {}
  }

  static Future<dynamic> _readCache(String name) async {
    final key = await _cacheKey(name);
    if (key == null) return null;
    try {
      final prefs = await SharedPreferences.getInstance();
      final raw = prefs.getString(key);
      if (raw == null || raw.trim().isEmpty) return null;
      final decoded = jsonDecode(raw);
      if (decoded is! Map) return null;
      return {
        'payload': decoded['payload'],
        'saved_at': '${decoded['saved_at'] ?? ''}',
      };
    } catch (_) {
      return null;
    }
  }

  static Map<String, dynamic> _markCacheMap(
    Map<dynamic, dynamic> source, {
    required bool offline,
    String savedAt = '',
  }) {
    final map = source.map((k, v) => MapEntry(k.toString(), v));
    map['_offline_cache'] = offline;
    if (savedAt.isNotEmpty) map['_cache_updated_at'] = savedAt;
    return map;
  }

  static Future<void> _refreshMapCache({
    required String cacheName,
    required Future<http.Response> Function() request,
    required String fallbackMessage,
    bool expectDataMap = false,
  }) async {
    try {
      final response = await request().timeout(_readTimeout);
      await ApiClient.handleUnauthorized(response);
      if (response.statusCode != 200) {
        throw Exception(_message(response, fallbackMessage));
      }
      final decoded = _decode(response);
      if (decoded is! Map) throw FormatException('$fallbackMessage Response is invalid.');
      if (expectDataMap && decoded['data'] is! Map) {
        throw FormatException('$fallbackMessage Response data is invalid.');
      }
      final map = _markCacheMap(decoded, offline: false);
      await _writeCache(cacheName, map);
      _networkReachable = true;
      _lastSuccessfulSync = DateTime.now();
    } catch (_) {
      _networkReachable = false;
    }
  }

  /// Offline-first / stale-while-revalidate read.
  ///
  /// If a local snapshot exists it is returned immediately, while a fresh copy
  /// is fetched in the background. This keeps the leave UI responsive like a
  /// messaging app even when the server or connection is slow.
  static Future<Map<String, dynamic>> _getMapCached({
    required String cacheName,
    required Future<http.Response> Function() request,
    required String fallbackMessage,
    bool expectDataMap = false,
  }) async {
    final cached = await _readCache(cacheName);
    final cachedPayload = cached is Map ? cached['payload'] : null;

    if (cachedPayload is Map) {
      // Do not block first paint on the network. The periodic UI refresh will
      // pick up the newly synchronized snapshot after this completes.
      _refreshMapCache(
        cacheName: cacheName,
        request: request,
        fallbackMessage: fallbackMessage,
        expectDataMap: expectDataMap,
      );
      final result = _markCacheMap(
        cachedPayload,
        offline: !_networkReachable,
        savedAt: '${cached['saved_at'] ?? ''}',
      );
      result['_cache_first'] = true;
      result['_sync_pending'] = true;
      return result;
    }

    try {
      final response = await request().timeout(_readTimeout);
      await ApiClient.handleUnauthorized(response);
      if (response.statusCode != 200) {
        throw Exception(_message(response, fallbackMessage));
      }
      final decoded = _decode(response);
      if (decoded is! Map) throw FormatException('$fallbackMessage Response is invalid.');
      if (expectDataMap && decoded['data'] is! Map) {
        throw FormatException('$fallbackMessage Response data is invalid.');
      }
      _networkReachable = true;
      _lastSuccessfulSync = DateTime.now();
      final map = _markCacheMap(decoded, offline: false);
      await _writeCache(cacheName, map);
      return map;
    } catch (error) {
      _networkReachable = false;
      rethrow;
    }
  }

  static Future<void> _invalidateCaches(Iterable<String> names) async {
    final prefs = await SharedPreferences.getInstance();
    for (final name in names) {
      final key = await _cacheKey(name);
      if (key != null) await prefs.remove(key);
    }
  }

  static Future<Map<String, dynamic>> getSetup() => _getMapCached(
        cacheName: 'setup',
        request: () async => http.get(
          _leaveUri(const {'action': 'setup'}),
          headers: await ApiClient.getHeaders(),
        ),
        fallbackMessage: 'Unable to load leave setup.',
      );

  static Future<Map<String, dynamic>> list({String scope = 'my'}) => _getMapCached(
        cacheName: 'list_$scope',
        request: () async => http.get(
          _leaveUri({'scope': scope}),
          headers: await ApiClient.getHeaders(),
        ),
        fallbackMessage: 'Unable to load leave applications.',
      );

  static Future<Map<String, dynamic>> myLedger({int? year}) {
    final suffix = year == null ? 'current' : '$year';
    final query = <String, String>{'action': 'my_ledger'};
    if (year != null) query['year'] = '$year';
    return _getMapCached(
      cacheName: 'my_ledger_$suffix',
      request: () async => http.get(
        _leaveUri(query),
        headers: await ApiClient.getHeaders(),
      ),
      fallbackMessage: 'Unable to load your leave-day ledger.',
    );
  }

  static Future<Map<String, dynamic>> getLeave(int id) async {
    final wrapped = await _getMapCached(
      cacheName: 'leave_$id',
      request: () async => http.get(
        _leaveUri({'id': '$id'}),
        headers: await ApiClient.getHeaders(),
      ),
      fallbackMessage: 'Unable to load leave application.',
      expectDataMap: true,
    );
    final data = wrapped['data'];
    if (data is! Map) throw const FormatException('Leave detail response is invalid.');
    final result = data.map((k, v) => MapEntry(k.toString(), v));
    result['_offline_cache'] = wrapped['_offline_cache'] == true;
    result['_cache_updated_at'] = wrapped['_cache_updated_at'];
    return result;
  }

  static Future<Map<String, dynamic>> create(Map<String, dynamic> payload) async {
    final response = await http
        .post(
          _leaveUri(),
          headers: await ApiClient.getHeaders(),
          body: jsonEncode(payload),
        )
        .timeout(const Duration(seconds: 25));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200 && response.statusCode != 201) {
      throw Exception(_message(response, 'Unable to submit leave application.'));
    }
    final decoded = _decode(response);
    if (decoded is! Map) throw const FormatException('Leave submission response is invalid.');
    await _invalidateCaches(['setup', 'list_my', 'list_action', 'list_completed', 'my_ledger_current']);
    return decoded.map((k, v) => MapEntry(k.toString(), v));
  }

  static Future<Map<String, dynamic>> action(
    int id,
    String action, {
    String remarks = '',
  }) async {
    final response = await http
        .post(
          _leaveUri({'id': '$id', 'action': action}),
          headers: await ApiClient.getHeaders(),
          body: jsonEncode({'remarks': remarks}),
        )
        .timeout(const Duration(seconds: 25));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200 && response.statusCode != 201) {
      throw Exception(_message(response, 'Unable to process leave action.'));
    }
    final decoded = _decode(response);
    if (decoded is! Map) throw const FormatException('Leave action response is invalid.');
    await _invalidateCaches(['setup', 'list_my', 'list_action', 'list_completed', 'my_ledger_current', 'hr_ledger']);
    return decoded.map((k, v) => MapEntry(k.toString(), v));
  }

  static Future<int> unreadCount() async {
    const cacheName = 'unread_count';
    final cached = await _readCache(cacheName);
    final cachedPayload = cached is Map ? cached['payload'] : null;
    if (cachedPayload is Map) {
      Future<void>(() async {
        try {
          final response = await http.get(
            _notificationUri(const {'action': 'count'}),
            headers: await ApiClient.getHeaders(),
          ).timeout(const Duration(seconds: 6));
          await ApiClient.handleUnauthorized(response);
          if (response.statusCode == 200) {
            final decoded = _decode(response);
            final count = decoded is Map ? int.tryParse('${decoded['unread_count'] ?? 0}') ?? 0 : 0;
            await _writeCache(cacheName, {'count': count});
            _networkReachable = true;
            _lastSuccessfulSync = DateTime.now();
          }
        } catch (_) {
          _networkReachable = false;
        }
      });
      return int.tryParse('${cachedPayload['count'] ?? 0}') ?? 0;
    }
    try {
      final response = await http.get(
        _notificationUri(const {'action': 'count'}),
        headers: await ApiClient.getHeaders(),
      ).timeout(const Duration(seconds: 6));
      await ApiClient.handleUnauthorized(response);
      if (response.statusCode != 200) throw Exception('Notification count unavailable.');
      final decoded = _decode(response);
      final count = decoded is Map ? int.tryParse('${decoded['unread_count'] ?? 0}') ?? 0 : 0;
      await _writeCache(cacheName, {'count': count});
      _networkReachable = true;
      _lastSuccessfulSync = DateTime.now();
      return count;
    } catch (_) {
      _networkReachable = false;
      return 0;
    }
  }

  static Future<List<Map<String, dynamic>>> notifications({int limit = 50}) async {
    final cacheName = 'notifications_$limit';
    final cached = await _readCache(cacheName);
    final cachedPayload = cached is Map ? cached['payload'] : null;
    if (cachedPayload is Map && cachedPayload['data'] is List) {
      Future<void>(() async {
        try {
          final response = await http.get(
            _notificationUri({'limit': '$limit'}),
            headers: await ApiClient.getHeaders(),
          ).timeout(_readTimeout);
          await ApiClient.handleUnauthorized(response);
          if (response.statusCode == 200) {
            final decoded = _decode(response);
            final raw = decoded is Map ? decoded['data'] : null;
            final rows = raw is List ? raw.whereType<Map>().map((e) => e.map((k,v)=>MapEntry(k.toString(),v))).toList() : <Map<String,dynamic>>[];
            await _writeCache(cacheName, {'data': rows});
            _networkReachable = true;
            _lastSuccessfulSync = DateTime.now();
          }
        } catch (_) {
          _networkReachable = false;
        }
      });
      final raw = cachedPayload['data'] as List;
      return raw.whereType<Map>().map((e) => e.map((k,v)=>MapEntry(k.toString(),v))).toList();
    }
    try {
      final response = await http.get(
        _notificationUri({'limit': '$limit'}),
        headers: await ApiClient.getHeaders(),
      ).timeout(_readTimeout);
      await ApiClient.handleUnauthorized(response);
      if (response.statusCode != 200) throw Exception(_message(response, 'Unable to load leave notifications.'));
      final decoded = _decode(response);
      final raw = decoded is Map ? decoded['data'] : null;
      final rows = raw is List ? raw.whereType<Map>().map((e) => e.map((k,v)=>MapEntry(k.toString(),v))).toList() : <Map<String,dynamic>>[];
      await _writeCache(cacheName, {'data': rows});
      _networkReachable = true;
      _lastSuccessfulSync = DateTime.now();
      return rows;
    } catch (_) {
      _networkReachable = false;
      rethrow;
    }
  }

  static Future<void> markNotificationRead(int id) async {
    final response = await http
        .post(
          _notificationUri({'id': '$id'}),
          headers: await ApiClient.getHeaders(),
        )
        .timeout(const Duration(seconds: 15));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_message(response, 'Unable to mark notification as read.'));
    }
  }

  static Future<void> markAllNotificationsRead() async {
    final response = await http
        .post(
          _notificationUri(const {'action': 'mark_all_read'}),
          headers: await ApiClient.getHeaders(),
        )
        .timeout(const Duration(seconds: 15));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_message(response, 'Unable to mark notifications as read.'));
    }
  }

  // ---------------------------------------------------------------------------
  // HR + EXECUTIVE LEAVE CONTROL CENTRE
  // ---------------------------------------------------------------------------

  static Future<Map<String, dynamic>> hrLedger() => _getMapCached(
        cacheName: 'hr_ledger',
        request: () async => http.get(
          _hrUri(const {'action': 'ledger'}),
          headers: await ApiClient.getHeaders(),
        ),
        fallbackMessage: 'Unable to load the HR leave ledger.',
      );

  static Future<Map<String, dynamic>> adjustBalance({
    required int userId,
    required String direction,
    required double days,
    required String reason,
  }) async {
    final response = await http
        .post(
          _hrUri({'action': 'adjust', 'user_id': '$userId'}),
          headers: await ApiClient.getHeaders(),
          body: jsonEncode({
            'direction': direction,
            'days': days,
            'reason': reason,
          }),
        )
        .timeout(const Duration(seconds: 25));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_message(response, 'Unable to adjust the employee leave balance.'));
    }
    final decoded = _decode(response);
    if (decoded is! Map) throw const FormatException('Leave adjustment response is invalid.');
    await _invalidateCaches(['hr_ledger', 'my_ledger_current', 'setup']);
    return decoded.map((k, v) => MapEntry(k.toString(), v));
  }

  static Future<Map<String, dynamic>> setAccountStatus({
    required int userId,
    required String operation,
    required String reason,
  }) async {
    final response = await http
        .post(
          _hrUri({'action': 'account_status', 'user_id': '$userId'}),
          headers: await ApiClient.getHeaders(),
          body: jsonEncode({
            'operation': operation,
            'reason': reason,
          }),
        )
        .timeout(const Duration(seconds: 25));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_message(response, 'Unable to update account status.'));
    }
    final decoded = _decode(response);
    if (decoded is! Map) throw const FormatException('Account status response is invalid.');
    await _invalidateCaches(['hr_ledger']);
    return decoded.map((k, v) => MapEntry(k.toString(), v));
  }

  static Future<Map<String, dynamic>> hrHistory(int userId, {int? year}) async {
    final suffix = year == null ? 'current' : '$year';
    return _getMapCached(
      cacheName: 'hr_history_${userId}_$suffix',
      request: () async {
        final query = <String, String>{'action': 'history', 'user_id': '$userId'};
        if (year != null) query['year'] = '$year';
        return http.get(_hrUri(query), headers: await ApiClient.getHeaders());
      },
      fallbackMessage: 'Unable to load employee leave history.',
    );
  }

  static Future<Map<String, dynamic>> runAccrual() async {
    final response = await http
        .post(
          _hrUri(const {'action': 'accrue'}),
          headers: await ApiClient.getHeaders(),
        )
        .timeout(const Duration(seconds: 30));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_message(response, 'Unable to synchronize monthly leave accrual.'));
    }
    final decoded = _decode(response);
    if (decoded is! Map) throw const FormatException('Leave accrual response is invalid.');
    await _invalidateCaches(['hr_ledger', 'my_ledger_current', 'setup']);
    return decoded.map((k, v) => MapEntry(k.toString(), v));
  }

  static String cleanError(Object error) {
    var text = error.toString().trim();
    if (text.startsWith('Exception: ')) text = text.substring('Exception: '.length);
    return text;
  }
}
