import 'dart:async';
import 'dart:convert';

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

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

// CV data is shown from local storage first. Network calls only refresh or sync it.
class CvService {
  const CvService._();

  static const _mineKey = 'rockview_cv_mine_v1';
  static const _directoryKey = 'rockview_cv_directory_v1';
  static const _pendingKey = 'rockview_cv_pending_v1';
  static const _photoKey = 'rockview_cv_photo_v1';
  static const _personPrefix = 'rockview_cv_person_v1_';
  static const _shortTimeout = Duration(seconds: 6);

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

  static Map<String, dynamic> _decode(http.Response response) {
    try {
      final value = jsonDecode(response.body);
      if (value is Map) return value.map((key, item) => MapEntry(key.toString(), item));
    } catch (_) {}
    throw Exception('The server returned an invalid response.');
  }

  static String _error(http.Response response) {
    try {
      final data = _decode(response);
      final message = data['detail'] ?? data['message'];
      if (message != null) return message.toString();
    } catch (_) {}
    return 'CV request failed (${response.statusCode}).';
  }

  static Map<String, dynamic>? _readMap(SharedPreferences prefs, String key) {
    final raw = prefs.getString(key);
    if (raw == null || raw.isEmpty) return null;
    try {
      final value = jsonDecode(raw);
      if (value is Map) return value.map((k, v) => MapEntry(k.toString(), v));
    } catch (_) {}
    return null;
  }

  static List<Map<String, dynamic>> _readRows(SharedPreferences prefs, String key) {
    final raw = prefs.getString(key);
    if (raw == null || raw.isEmpty) return [];
    try {
      final value = jsonDecode(raw);
      if (value is List) {
        return value.whereType<Map>().map((row) => row.map((k, v) => MapEntry(k.toString(), v))).toList();
      }
    } catch (_) {}
    return [];
  }

  static Future<void> _writeMap(SharedPreferences prefs, String key, Map<String, dynamic> data) async {
    await prefs.setString(key, jsonEncode(data));
  }

  static Map<String, dynamic> _markCached(Map<String, dynamic> data, {bool pending = false}) => {
    ...data,
    '_offline_cached': true,
    '_offline_pending': pending,
  };

  // Loads the saved CV immediately. Call with refresh:true from the refresh button.
  static Future<Map<String, dynamic>> mine({bool refresh = false}) async {
    final prefs = await SharedPreferences.getInstance();
    final cached = _readMap(prefs, _mineKey);
    final pending = _readMap(prefs, _pendingKey);
    if (!refresh && cached != null) {
      return _markCached(_withLocalPhoto(cached, prefs), pending: pending != null);
    }

    try {
      if (pending != null) await _syncPending(prefs);

      final response = await http.get(_uri(), headers: await ApiClient.getHeaders()).timeout(_shortTimeout);
      await ApiClient.handleUnauthorized(response);
      if (response.statusCode != 200) throw Exception(_error(response));
      final data = _dataFromResponse(response);
      final withPhoto = _withLocalPhoto(data, prefs);
      await _writeMap(prefs, _mineKey, withPhoto);
      return withPhoto;
    } catch (error) {
      if (cached != null) return _markCached(_withLocalPhoto(cached, prefs), pending: pending != null);
      throw Exception('No saved CV is available offline yet. Connect once to load your profile. ${cleanError(error)}');
    }
  }

  // Saves locally immediately. A small background request syncs the pending copy.
  static Future<Map<String, dynamic>> save(Map<String, dynamic> payload) async {
    final prefs = await SharedPreferences.getInstance();
    final previous = _readMap(prefs, _mineKey) ?? <String, dynamic>{};
    final profile = payload['profile'] is Map ? Map<String, dynamic>.from(payload['profile'] as Map) : <String, dynamic>{};
    final entries = payload['entries'] is Map ? Map<String, dynamic>.from(payload['entries'] as Map) : <String, dynamic>{};
    final photoData = '${payload['photo_data'] ?? ''}';
    final local = <String, dynamic>{...previous, ...profile, 'entries': entries};
    if (photoData.isNotEmpty) await prefs.setString(_photoKey, photoData);

    // Device copy is committed before the internet is contacted.
    await _writeMap(prefs, _mineKey, local);
    await _writeMap(prefs, _pendingKey, {'profile': profile, 'entries': entries, 'has_photo': photoData.isNotEmpty});
    unawaited(_syncPending(prefs));
    return {
      'offline': true,
      'message': 'Saved on this device. Any photo and changes will sync when connected.',
      'data': _markCached(_withLocalPhoto(local, prefs), pending: true),
    };
  }

  static Future<void> _syncPending(SharedPreferences prefs) async {
    final pending = _readMap(prefs, _pendingKey);
    if (pending == null) return;
    try {
      final payload = <String, dynamic>{'profile': pending['profile'], 'entries': pending['entries']};
      if (pending['has_photo'] == true) {
        final photoData = prefs.getString(_photoKey);
        if (photoData != null && photoData.isNotEmpty) payload['photo_data'] = photoData;
      }
      final response = await http.post(
        _uri(), headers: await ApiClient.getHeaders(), body: jsonEncode(payload),
      ).timeout(_shortTimeout);
      await ApiClient.handleUnauthorized(response);
      if (response.statusCode != 200) return;
      final saved = _dataFromResponse(response);
      await _writeMap(prefs, _mineKey, saved);
      await prefs.remove(_pendingKey);
    } catch (_) {
      // Keep the draft queued; the next manual refresh will try again.
    }
  }

  // Admin directory: cache results for this app session and filter locally.
  static List<Map<String, dynamic>> _directoryMemory = [];
  static bool _directoryLoaded = false;

  static Future<List<Map<String, dynamic>>> directory({String search = '', bool refresh = false}) async {
    final prefs = await SharedPreferences.getInstance();
    if (!_directoryLoaded) {
      _directoryMemory = _readRows(prefs, _directoryKey);
      _directoryLoaded = _directoryMemory.isNotEmpty;
    }
    if (!refresh && _directoryLoaded) return _filterDirectory(_directoryMemory, search);

    try {
      final response = await http.get(_uri({'scope': 'directory'}), headers: await ApiClient.getHeaders()).timeout(_shortTimeout);
      await ApiClient.handleUnauthorized(response);
      if (response.statusCode != 200) throw Exception(_error(response));
      final rows = _decode(response)['data'];
      _directoryMemory = rows is List ? rows.whereType<Map>().map((row) {
        final item = row.map((k, v) => MapEntry(k.toString(), v));
        item['account_photo'] = _absolutePhoto('${item['account_photo'] ?? ''}');
        return item;
      }).toList() : [];
      _directoryLoaded = true;
      await prefs.setString(_directoryKey, jsonEncode(_directoryMemory));
      return _filterDirectory(_directoryMemory, search);
    } catch (error) {
      if (_directoryLoaded) return _filterDirectory(_directoryMemory, search);
      throw Exception('The employee list has not been cached on this device yet. ${cleanError(error)}');
    }
  }

  static List<Map<String, dynamic>> _filterDirectory(List<Map<String, dynamic>> rows, String search) {
    final query = search.trim().toLowerCase();
    if (query.isEmpty) return List<Map<String, dynamic>>.from(rows);
    return rows.where((row) => [row['full_name'], row['account_email'], row['campus'], row['program'], row['user_id']]
        .any((value) => '${value ?? ''}'.toLowerCase().contains(query))).toList();
  }

  static Future<Map<String, dynamic>> getCv(int id, {bool refresh = false}) async {
    final prefs = await SharedPreferences.getInstance();
    final key = '$_personPrefix$id';
    final cached = _readMap(prefs, key);
    if (!refresh && cached != null) return _markCached(cached);
    try {
      final response = await http.get(_uri({'id': '$id'}), headers: await ApiClient.getHeaders()).timeout(_shortTimeout);
      await ApiClient.handleUnauthorized(response);
      if (response.statusCode != 200) throw Exception(_error(response));
      final data = _dataFromResponse(response);
      await _writeMap(prefs, key, data);
      return data;
    } catch (error) {
      if (cached != null) return _markCached(cached);
      throw Exception('This CV is not available offline because it has not been opened on this device yet. ${cleanError(error)}');
    }
  }

  static Map<String, dynamic> _withLocalPhoto(Map<String, dynamic> data, SharedPreferences prefs) {
    final photo = prefs.getString(_photoKey);
    return photo == null || photo.isEmpty ? data : {...data, '_photo_base64': photo};
  }

  static String _absolutePhoto(String path) {
    final value = path.trim();
    if (value.isEmpty || value.startsWith('http://') || value.startsWith('https://') || value.startsWith('data:')) return value;
    final base = ApiClient.baseUrl.replaceFirst(RegExp(r'/+$'), '');
    final clean = value.replaceFirst(RegExp(r'^/+'), '');
    if (clean.startsWith('uploads/cv/')) return '$base/api/$clean';
    return '$base/$clean';
  }

  static Map<String, dynamic> _dataFromResponse(http.Response response) {
    final data = _decode(response)['data'];
    if (data is Map) {
      final row = data.map((key, value) => MapEntry(key.toString(), value));
      row['photo_url'] = _absolutePhoto('${row['photo_url'] ?? ''}');
      row['account_photo'] = _absolutePhoto('${row['account_photo'] ?? ''}');
      return row;
    }
    throw Exception('The CV data could not be read.');
  }

  // Call this from the app's logout handler to protect cached staff information.
  static Future<void> clearLocalCache() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_mineKey);
    await prefs.remove(_pendingKey);
    await prefs.remove(_photoKey);
    await prefs.remove(_directoryKey);
    final personKeys = prefs.getKeys().where((key) => key.startsWith(_personPrefix)).toList();
    for (final key in personKeys) { await prefs.remove(key); }
    _directoryMemory = [];
    _directoryLoaded = false;
  }

  static String cleanError(Object error) => error.toString().replaceFirst('Exception: ', '').trim();
}
