import 'dart:convert';

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

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

class RequestWorkflowService {
  static const Duration _timeout = Duration(seconds: 25);

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

  static dynamic _decode(http.Response response) {
    final body = utf8.decode(response.bodyBytes, allowMalformed: true).trim();
    if (body.isEmpty) return null;
    try {
      return jsonDecode(body);
    } catch (_) {
      final objectAt = body.lastIndexOf('{');
      final arrayAt = body.lastIndexOf('[');
      final start = objectAt > arrayAt ? objectAt : arrayAt;
      if (start >= 0) {
        try {
          return jsonDecode(body.substring(start));
        } catch (_) {}
      }
      throw const FormatException('The request workflow API returned invalid JSON.');
    }
  }

  static String _errorMessage(http.Response response, String fallback) {
    try {
      final decoded = _decode(response);
      if (decoded is Map) {
        for (final key in const ['detail', 'message', 'error']) {
          final value = decoded[key];
          if (value != null && value.toString().trim().isNotEmpty) {
            return value.toString().trim();
          }
        }
      }
    } catch (_) {}
    return '$fallback (HTTP ${response.statusCode})';
  }

  static Future<Map<String, dynamic>> _getMap(
    String file, {
    Map<String, String>? query,
  }) async {
    final response = await http
        .get(_uri(file, query), headers: await ApiClient.getHeaders())
        .timeout(_timeout);
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to load request workflow data.'));
    }
    final decoded = _decode(response);
    if (decoded is Map) {
      return decoded.map((key, value) => MapEntry(key.toString(), value));
    }
    throw const FormatException('The request workflow API returned an invalid object.');
  }

  static Future<List<Map<String, dynamic>>> _getList(
    String file, {
    Map<String, String>? query,
  }) async {
    final response = await http
        .get(_uri(file, query), headers: await ApiClient.getHeaders())
        .timeout(_timeout);
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to load request workflow records.'));
    }
    final decoded = _decode(response);
    dynamic rows = decoded;
    if (decoded is Map) {
      rows = decoded['data'] ?? decoded['requests'] ?? decoded['notifications'];
    }
    if (rows is! List) return const <Map<String, dynamic>>[];
    return rows
        .whereType<Map>()
        .map((item) => item.map((key, value) => MapEntry(key.toString(), value)))
        .toList();
  }

  static Future<Map<String, dynamic>> getDirectory({String? campus}) {
    final query = <String, String>{'action': 'directory'};
    if (campus != null && campus.trim().isNotEmpty) query['campus'] = campus.trim();
    return _getMap('request_workflow.php', query: query);
  }

  static Future<Map<String, dynamic>> getSummary() {
    return _getMap('request_workflow.php', query: const {'action': 'summary'});
  }

  static Future<Map<String, dynamic>> getOfficeHolders({String? campus}) {
    final query = <String, String>{};
    if (campus != null && campus.trim().isNotEmpty) query['campus'] = campus.trim();
    return _getMap('request_office_holders.php', query: query);
  }

  static Future<Map<String, dynamic>> assignOfficeHolder({
    required int positionId,
    required int userId,
    required String campus,
  }) async {
    final response = await http
        .post(
          _uri('request_office_holders.php'),
          headers: await ApiClient.getHeaders(),
          body: jsonEncode({
            'position_id': positionId,
            'user_id': userId,
            'campus': campus.trim(),
          }),
        )
        .timeout(_timeout);
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200 && response.statusCode != 201) {
      throw Exception(_errorMessage(response, 'Unable to assign the office holder.'));
    }
    final decoded = _decode(response);
    if (decoded is Map) {
      return decoded.map((key, value) => MapEntry(key.toString(), value));
    }
    return const <String, dynamic>{};
  }

  static Future<void> removeOfficeHolder(int assignmentId) async {
    final response = await http
        .delete(
          _uri('request_office_holders.php', {'id': '$assignmentId'}),
          headers: await ApiClient.getHeaders(),
        )
        .timeout(_timeout);
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200 && response.statusCode != 204) {
      throw Exception(_errorMessage(response, 'Unable to remove the office holder.'));
    }
  }

  static Future<List<Map<String, dynamic>>> getRequests({
    required String scope,
    String search = '',
  }) {
    return _getList(
      'request_workflow.php',
      query: {
        'scope': scope,
        if (search.trim().isNotEmpty) 'search': search.trim(),
      },
    );
  }

  static Future<Map<String, dynamic>> getRequest(int id) {
    return _getMap('request_workflow.php', query: {'id': '$id'});
  }

  /// The backend controls the first destination. The client deliberately does
  /// not send recipient position/campus: every new request goes to the
  /// Registrar of the authenticated user's campus.
  static Future<int> createRequest({
    required String reference,
    required String body,
    required String priority,
    required String category,
    String? senderPositionHint,
    double? amount,
    Map<String, dynamic>? tableData,
  }) async {
    final response = await http
        .post(
          _uri('request_workflow.php'),
          headers: await ApiClient.getHeaders(),
          body: jsonEncode({
            'reference': reference.trim(),
            'body': body.trim(),
            'priority': priority,
            'category': category,
            if (senderPositionHint != null && senderPositionHint.trim().isNotEmpty)
              'sender_position_hint': senderPositionHint.trim(),
            if (amount != null) 'amount': amount,
            if (tableData != null) 'table_data': tableData,
          }),
        )
        .timeout(_timeout);
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 201 && response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to dispatch the request.'));
    }
    final decoded = _decode(response);
    if (decoded is Map) {
      return int.tryParse('${decoded['id'] ?? decoded['request_id'] ?? 0}') ?? 0;
    }
    return 0;
  }

  /// Approval/escalation/cancellation permissions are enforced by PHP using
  /// the authenticated administrator account, its database position and the
  /// request campus. The client cannot choose an arbitrary next office.
  static Future<Map<String, dynamic>> actOnRequest({
    required int requestId,
    required String action,
    String remarks = '',
  }) async {
    final response = await http
        .put(
          _uri('request_workflow.php', {'id': '$requestId'}),
          headers: await ApiClient.getHeaders(),
          body: jsonEncode({
            'action': action,
            'remarks': remarks.trim(),
          }),
        )
        .timeout(_timeout);
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to process the request.'));
    }
    final decoded = _decode(response);
    if (decoded is Map) {
      return decoded.map((key, value) => MapEntry(key.toString(), value));
    }
    return const <String, dynamic>{};
  }

  static Future<void> cancelRequest(int requestId, {String remarks = ''}) async {
    await actOnRequest(requestId: requestId, action: 'cancel', remarks: remarks);
  }

  static Future<List<Map<String, dynamic>>> getNotifications({bool unreadOnly = false}) {
    return _getList(
      'request_notifications.php',
      query: {'unread_only': unreadOnly ? '1' : '0'},
    );
  }

  static Future<int> getUnreadNotificationCount() async {
    final data = await _getMap(
      'request_notifications.php',
      query: const {'action': 'count'},
    );
    return int.tryParse('${data['unread_count'] ?? 0}') ?? 0;
  }

  static Future<void> markNotificationRead(int notificationId) async {
    await _updateNotification({'action': 'mark_read', 'id': notificationId});
  }

  static Future<void> markAllNotificationsRead() async {
    await _updateNotification(const {'action': 'mark_all_read'});
  }

  static Future<void> _updateNotification(Map<String, dynamic> body) async {
    final response = await http
        .put(
          _uri('request_notifications.php'),
          headers: await ApiClient.getHeaders(),
          body: jsonEncode(body),
        )
        .timeout(_timeout);
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to update notifications.'));
    }
  }

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