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

import 'package:crypto/crypto.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

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

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

  static final ValueNotifier<int> offlineRevision = ValueNotifier<int>(0);
  static const _shortTimeout = Duration(seconds: 6);

  static void _throwIfForbidden(http.Response response) {
    if (response.statusCode == 403) throw CvAccessDeniedException(_error(response));
  }

  static Future<_CvKeys> _keys() async {
    final user = await DatabaseService.getLocalUser();
    final identity = '${user?.identifierId ?? ''}|${user?.email.trim().toLowerCase() ?? ''}';
    final scope = sha256.convert(utf8.encode(identity)).toString().substring(0, 20);
    return _CvKeys(
      mine: 'rockview_cv_mine_v2_$scope',
      directory: 'rockview_cv_directory_v2_$scope',
      pending: 'rockview_cv_pending_v2_$scope',
      photo: 'rockview_cv_photo_v2_$scope',
      personPrefix: 'rockview_cv_person_v2_${scope}_',
      userId: user?.identifierId ?? 0,
      role: user?.role.toLowerCase().trim() ?? '',
    );
  }

  static bool _canViewEmployeeCv(_CvKeys keys, int id) =>
      keys.role == 'admin' || (id > 0 && id == keys.userId);

  static void _refreshQuietly(Uri uri, Map<String, String> headers, Future<void> Function(http.Response) save) {
    unawaited(() async {
      try {
        final response = await ApiClient.offlineFirstGet(uri, headers: headers,
            timeout: _shortTimeout, forceRefresh: true);
        await save(response);
      } catch (_) {
        // Preserve the last valid local snapshot on refresh failures.
      }
    }());
  }

  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 {
    final encoded = jsonEncode(data);
    if (prefs.getString(key) == encoded) return;
    await prefs.setString(key, encoded);
    offlineRevision.value++;
  }

  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 keys = await _keys();
    final cached = _readMap(prefs, keys.mine);
    final pending = _readMap(prefs, keys.pending);
    if (!refresh && cached != null) {
      _refreshQuietly(_uri(), await ApiClient.getHeaders(), (response) async {
        if (response.statusCode == 403) {
          await prefs.remove(keys.mine);
          return;
        }
        if (response.statusCode != 200) return;
        if (_readMap(prefs, keys.pending) != null) return;
        final latest = _dataFromResponse(response);
        await _writeMap(prefs, keys.mine, latest);
      });
      return _markCached(_withLocalPhoto(cached, prefs, keys.photo), pending: pending != null);
    }

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

      final response = await ApiClient.offlineFirstGet(_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, keys.photo);
      await _writeMap(prefs, keys.mine, withPhoto);
      return withPhoto;
    } catch (error) {
      if (cached != null) return _markCached(_withLocalPhoto(cached, prefs, keys.photo), 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 keys = await _keys();
    final previous = _readMap(prefs, keys.mine) ?? <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(keys.photo, photoData);

    // Device copy is committed before the internet is contacted.
    await _writeMap(prefs, keys.mine, local);
    await _writeMap(prefs, keys.pending, {'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, keys.photo), pending: true),
    };
  }

  static Future<void> _syncPending(SharedPreferences prefs) async {
    final keys = await _keys();
    final pending = _readMap(prefs, keys.pending);
    if (pending == null) return;
    try {
      final payload = <String, dynamic>{'profile': pending['profile'], 'entries': pending['entries']};
      if (pending['has_photo'] == true) {
        final photoData = prefs.getString(keys.photo);
        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, keys.mine, saved);
      await prefs.remove(keys.pending);
    } 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 String? _directoryMemoryKey;

  static Future<List<Map<String, dynamic>>> directory({String search = '', bool refresh = false}) async {
    final prefs = await SharedPreferences.getInstance();
    final keys = await _keys();
    if (keys.role != 'admin') {
      throw Exception('Employee CV directory access is restricted to administrators.');
    }
    if (_directoryMemoryKey != keys.directory) {
      _directoryMemory = [];
      _directoryLoaded = false;
      _directoryMemoryKey = keys.directory;
    }
    if (!_directoryLoaded) {
      _directoryMemory = _readRows(prefs, keys.directory);
      _directoryLoaded = _directoryMemory.isNotEmpty;
    }
    if (!refresh && _directoryLoaded) {
      _refreshQuietly(_uri({'scope': 'directory'}), await ApiClient.getHeaders(), (response) async {
        if (response.statusCode == 403) {
          await prefs.remove(keys.directory);
          _directoryMemory = [];
          _directoryLoaded = false;
          return;
        }
        if (response.statusCode != 200) return;
        final rows = _decode(response)['data'];
        if (rows is! List) return;
        _directoryMemory = 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();
        final encoded = jsonEncode(_directoryMemory);
        if (prefs.getString(keys.directory) != encoded) {
          await prefs.setString(keys.directory, encoded);
          offlineRevision.value++;
        }
      });
      return _filterDirectory(_directoryMemory, search);
    }

    try {
      final response = await ApiClient.offlineFirstGet(_uri({'scope': 'directory'}), headers: await ApiClient.getHeaders()).timeout(_shortTimeout);
      _throwIfForbidden(response);
      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;
      final encoded = jsonEncode(_directoryMemory);
      if (prefs.getString(keys.directory) != encoded) {
        await prefs.setString(keys.directory, encoded);
        offlineRevision.value++;
      }
      return _filterDirectory(_directoryMemory, search);
    } catch (error) {
      if (error is CvAccessDeniedException) {
        _directoryMemory = [];
        _directoryLoaded = false;
        await prefs.remove(keys.directory);
        rethrow;
      }
      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 keys = await _keys();
    if (!_canViewEmployeeCv(keys, id)) {
      throw Exception(id == keys.userId
          ? 'Use My CV to view your own profile.'
          : 'You can only view your own CV.');
    }
    final key = '${keys.personPrefix}$id';
    final cached = _readMap(prefs, key);
    if (!refresh && cached != null) {
      _refreshQuietly(_uri({'id': '$id'}), await ApiClient.getHeaders(), (response) async {
        if (response.statusCode == 403) {
          await prefs.remove(key);
          return;
        }
        if (response.statusCode != 200) return;
        await _writeMap(prefs, key, _dataFromResponse(response));
      });
      return _markCached(cached);
    }
    try {
      final response = await ApiClient.offlineFirstGet(_uri({'id': '$id'}), headers: await ApiClient.getHeaders()).timeout(_shortTimeout);
      _throwIfForbidden(response);
      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 (error is CvAccessDeniedException) {
        await prefs.remove(key);
        rethrow;
      }
      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, String photoKey) {
    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();
    final keys = await _keys();
    await prefs.remove(keys.mine);
    await prefs.remove(keys.pending);
    await prefs.remove(keys.photo);
    await prefs.remove(keys.directory);
    final personKeys = prefs.getKeys().where((key) => key.startsWith(keys.personPrefix)).toList();
    for (final key in personKeys) { await prefs.remove(key); }
    _directoryMemory = [];
    _directoryLoaded = false;
  }

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

class _CvKeys {
  final String mine, directory, pending, photo, personPrefix, role;
  final int userId;
  const _CvKeys({required this.mine, required this.directory, required this.pending,
    required this.photo, required this.personPrefix, required this.userId, required this.role});
}

class CvAccessDeniedException implements Exception {
  final String message;
  const CvAccessDeniedException(this.message);
  @override
  String toString() => message;
}
