// lib/core/services/chat_media_service.dart

import 'dart:convert';
import 'dart:io';

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

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

class ChatMediaUpload {
  final int id;
  final String token;
  final String chatId;
  final String fileName;
  final String fileType;
  final String mimeType;
  final int sizeBytes;
  final String fileUrl;
  final String downloadUrl;
  final String? createdAt;

  const ChatMediaUpload({
    required this.id,
    required this.token,
    required this.chatId,
    required this.fileName,
    required this.fileType,
    required this.mimeType,
    required this.sizeBytes,
    required this.fileUrl,
    required this.downloadUrl,
    this.createdAt,
  });

  factory ChatMediaUpload.fromJson(Map<String, dynamic> json) {
    return ChatMediaUpload(
      id: _asInt(json['id']),
      token: _asText(json['token']),
      chatId: _asText(json['chat_id']),
      fileName: _asText(json['file_name'], 'Attachment'),
      fileType: _asText(json['file_type'], 'document'),
      mimeType: _asText(json['mime_type'], 'application/octet-stream'),
      sizeBytes: _asInt(json['size_bytes']),
      fileUrl: _asText(json['file_url']),
      downloadUrl: _asText(json['download_url']),
      createdAt: json['created_at']?.toString(),
    );
  }

  static int _asInt(dynamic value) {
    if (value is int) return value;
    return int.tryParse(value?.toString() ?? '') ?? 0;
  }

  static String _asText(dynamic value, [String fallback = '']) {
    final text = value?.toString().trim() ?? '';
    return text.isEmpty || text.toLowerCase() == 'null' ? fallback : text;
  }
}

class ChatMediaService {
  ChatMediaService._();

  static Future<ChatMediaUpload> uploadFile({
    required String chatId,
    required File file,
    required String fileName,
  }) async {
    if (chatId.trim().isEmpty) {
      throw ArgumentError('chatId cannot be empty.');
    }
    if (!await file.exists()) {
      throw Exception('$fileName could not be found on this device.');
    }

    final request = http.MultipartRequest(
      'POST',
      Uri.parse('${ApiClient.baseUrl}/api/chat_media.php'),
    );

    final headers = await ApiClient.getHeaders();
    headers.remove('Content-Type');
    request.headers.addAll(headers);
    request.fields['chat_id'] = chatId;
    request.files.add(
      await http.MultipartFile.fromPath(
        'file',
        file.path,
        filename: fileName,
      ),
    );

    final streamed = await request.send().timeout(const Duration(seconds: 120));
    final response = await http.Response.fromStream(streamed);
    await ApiClient.handleUnauthorized(response);

    if (response.statusCode != 200 && response.statusCode != 201) {
      throw Exception(_errorMessage(response, 'Unable to upload the attachment.'));
    }

    final decoded = _decode(response.body);
    if (decoded is! Map) {
      throw const FormatException('The chat media server returned an invalid response.');
    }

    final media = decoded['media'];
    if (media is! Map) {
      throw const FormatException('The upload succeeded but media details were missing.');
    }

    final upload = ChatMediaUpload.fromJson(
      media.map((key, value) => MapEntry(key.toString(), value)),
    );

    if (upload.fileUrl.isEmpty) {
      throw const FormatException('The upload response did not contain a file URL.');
    }
    return upload;
  }

  static Future<void> deleteMedia(String token) async {
    if (token.trim().isEmpty) return;
    final response = await http.delete(
      Uri.parse('${ApiClient.baseUrl}/api/chat_media.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode({'token': token}),
    ).timeout(const Duration(seconds: 30));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200 && response.statusCode != 204) {
      throw Exception(_errorMessage(response, 'Unable to remove the attachment.'));
    }
  }

  static Future<Map<String, String>> downloadHeaders() async {
    final headers = await ApiClient.getHeaders();
    headers.remove('Content-Type');
    return headers;
  }

  static dynamic _decode(String raw) {
    var body = raw.trim();
    if (body.startsWith('\ufeff')) body = body.substring(1);
    try {
      return jsonDecode(body);
    } catch (_) {
      final firstBrace = body.indexOf('{');
      final firstBracket = body.indexOf('[');
      final starts = <int>[
        if (firstBrace >= 0) firstBrace,
        if (firstBracket >= 0) firstBracket,
      ]..sort();
      for (final start in starts) {
        try {
          return jsonDecode(body.substring(start));
        } catch (_) {}
      }
      final clean = body
          .replaceAll(RegExp(r'<[^>]*>'), ' ')
          .replaceAll(RegExp(r'\s+'), ' ')
          .trim();
      final preview = clean.length > 320 ? '${clean.substring(0, 320)}...' : clean;
      throw FormatException(
        preview.isEmpty
            ? 'The chat media server returned an empty response.'
            : 'The chat media server returned a non-JSON response: $preview',
      );
    }
  }

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