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

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

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

class ConnectSocialService {
  static dynamic _decode(http.Response response) {
    final body = response.body.trim();
    if (body.isEmpty) return null;
    try {
      return jsonDecode(body);
    } catch (_) {
      throw FormatException(
        'The server returned an invalid response (HTTP ${response.statusCode}).',
      );
    }
  }

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

  static Map<String, dynamic> _map(dynamic raw) {
    if (raw is Map) {
      return raw.map((key, value) => MapEntry(key.toString(), value));
    }
    return <String, dynamic>{};
  }

  static bool _bool(dynamic value) {
    if (value is bool) return value;
    final text = '${value ?? ''}'.trim().toLowerCase();
    return text == '1' || text == 't' || text == 'true' || text == 'yes';
  }

  static int _int(dynamic value) => int.tryParse('${value ?? 0}') ?? 0;

  static String mediaUrl(String? raw) {
    final value = raw?.trim() ?? '';
    if (value.isEmpty) return '';
    if (value.startsWith('http://') || value.startsWith('https://')) return value;
    final normalized = value.startsWith('/') ? value.substring(1) : value;
    return '${ApiClient.baseUrl}/$normalized';
  }

  static List<Map<String, dynamic>> _normalizeMedia(dynamic raw) {
    dynamic value = raw;
    if (value is String && value.trim().isNotEmpty) {
      try {
        value = jsonDecode(value);
      } catch (_) {
        value = const <dynamic>[];
      }
    }
    if (value is! List) return <Map<String, dynamic>>[];

    return value.whereType<Map>().map((item) {
      final row = _map(item);
      row['id'] = _int(row['id']);
      row['size_bytes'] = _int(row['size_bytes']);
      row['url'] = mediaUrl(row['file_path']?.toString());
      return row;
    }).toList();
  }

  static Map<String, dynamic> _normalizePost(dynamic raw) {
    final item = _map(raw);
    item['id'] = _int(item['id']);
    item['likes_count'] = _int(item['likes_count']);
    item['comments_count'] = _int(item['comments_count']);
    item['liked_by_me'] = _bool(item['liked_by_me']);
    item['media'] = _normalizeMedia(item['media']);
    return item;
  }

  static Future<List<Map<String, dynamic>>> getPosts({
    int page = 1,
    int limit = 25,
    String search = '',
  }) async {
    final uri = Uri.parse('${ApiClient.baseUrl}/api/connect_posts.php').replace(
      queryParameters: <String, String>{
        'page': '$page',
        'limit': '$limit',
        if (search.trim().isNotEmpty) 'q': search.trim(),
      },
    );

    final response = await ApiClient.offlineFirstGet(uri, headers: await ApiClient.getHeaders())
        .timeout(const Duration(seconds: 25));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_error(response, 'Unable to load posts.'));
    }

    final decoded = _decode(response);
    final raw = decoded is Map ? decoded['data'] : decoded;
    if (raw is! List) return <Map<String, dynamic>>[];
    return raw.map(_normalizePost).toList();
  }

  static Future<Map<String, dynamic>> createPost({
    required String content,
    List<File> images = const <File>[],
    File? video,
    String? taggedName,
    String? location,
  }) async {
    if (images.length > 6) {
      throw Exception('A post can contain at most 6 pictures.');
    }
    if (video != null && images.isNotEmpty) {
      throw Exception('Choose either pictures or one video for a single post.');
    }
    if (content.trim().isEmpty && images.isEmpty && video == null) {
      throw Exception('Write something or attach media before posting.');
    }

    const imageLimit = 10 * 1024 * 1024;
    const videoLimit = 50 * 1024 * 1024;
    for (final image in images) {
      if (await image.length() > imageLimit) {
        throw Exception(
          '${image.path.split(Platform.pathSeparator).last} is larger than 10 MB.',
        );
      }
    }
    if (video != null && await video.length() > videoLimit) {
      throw Exception('The selected video is larger than 50 MB.');
    }

    final request = http.MultipartRequest(
      'POST',
      Uri.parse('${ApiClient.baseUrl}/api/connect_posts.php'),
    );
    final headers = await ApiClient.getHeaders();
    headers.remove('Content-Type');
    request.headers.addAll(headers);
    request.fields['content'] = content.trim();
    if (taggedName != null && taggedName.trim().isNotEmpty) {
      request.fields['tagged_name'] = taggedName.trim();
    }
    if (location != null && location.trim().isNotEmpty) {
      request.fields['location'] = location.trim();
    }

    for (final image in images) {
      request.files.add(await http.MultipartFile.fromPath('media[]', image.path));
    }
    if (video != null) {
      request.files.add(await http.MultipartFile.fromPath('media[]', video.path));
    }

    final streamed = await request.send().timeout(const Duration(seconds: 180));
    final response = await http.Response.fromStream(streamed);
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200 && response.statusCode != 201) {
      throw Exception(_error(response, 'Unable to create the post.'));
    }

    final decoded = _decode(response);
    if (decoded is Map && decoded['data'] is Map) {
      return _normalizePost(decoded['data']);
    }
    return <String, dynamic>{};
  }

  static Future<Map<String, dynamic>> toggleLike(int postId) async {
    final response = await http
        .post(
          Uri.parse('${ApiClient.baseUrl}/api/connect_post_likes.php'),
          headers: await ApiClient.getHeaders(),
          body: jsonEncode({'post_id': postId}),
        )
        .timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_error(response, 'Unable to update the like.'));
    }
    return _map(_decode(response));
  }

  static Future<List<Map<String, dynamic>>> getComments(int postId) async {
    final uri = Uri.parse('${ApiClient.baseUrl}/api/connect_post_comments.php')
        .replace(queryParameters: {'post_id': '$postId'});
    final response = await ApiClient.offlineFirstGet(uri, headers: await ApiClient.getHeaders())
        .timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_error(response, 'Unable to load comments.'));
    }
    final decoded = _decode(response);
    final raw = decoded is Map ? decoded['data'] : decoded;
    if (raw is! List) return <Map<String, dynamic>>[];
    return raw.whereType<Map>().map((item) {
      final row = _map(item);
      row['id'] = _int(row['id']);
      if (row['parent_id'] != null) row['parent_id'] = _int(row['parent_id']);
      if (row['image_path'] != null && row['image_path'].toString().trim().isNotEmpty) {
        row['image_url'] = mediaUrl(row['image_path'].toString());
      }
      return row;
    }).toList();
  }

  static Future<Map<String, dynamic>> createComment({
    required int postId,
    required String content,
    int? parentId,
    File? image,
  }) async {
    if (content.trim().isEmpty && image == null) {
      throw Exception('Write a comment or attach a picture.');
    }
    if (image != null && await image.length() > 8 * 1024 * 1024) {
      throw Exception('Comment pictures must not exceed 8 MB.');
    }

    final request = http.MultipartRequest(
      'POST',
      Uri.parse('${ApiClient.baseUrl}/api/connect_post_comments.php'),
    );
    final headers = await ApiClient.getHeaders();
    headers.remove('Content-Type');
    request.headers.addAll(headers);
    request.fields['post_id'] = '$postId';
    request.fields['content'] = content.trim();
    if (parentId != null) request.fields['parent_id'] = '$parentId';
    if (image != null) {
      request.files.add(await http.MultipartFile.fromPath('image', image.path));
    }

    final streamed = await request.send().timeout(const Duration(seconds: 75));
    final response = await http.Response.fromStream(streamed);
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200 && response.statusCode != 201) {
      throw Exception(_error(response, 'Unable to add the comment.'));
    }
    final decoded = _decode(response);
    if (decoded is Map && decoded['data'] is Map) {
      final row = _map(decoded['data']);
      row['id'] = _int(row['id']);
      if (row['parent_id'] != null) row['parent_id'] = _int(row['parent_id']);
      if (row['image_path'] != null && row['image_path'].toString().trim().isNotEmpty) {
        row['image_url'] = mediaUrl(row['image_path'].toString());
      }
      return row;
    }
    return <String, dynamic>{};
  }

  static Future<int> getUnreadNotificationCount() async {
    final uri = Uri.parse('${ApiClient.baseUrl}/api/connect_notifications.php')
        .replace(queryParameters: const {'mode': 'count'});
    final response = await ApiClient.offlineFirstGet(uri, headers: await ApiClient.getHeaders())
        .timeout(const Duration(seconds: 15));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) return 0;
    final decoded = _decode(response);
    return decoded is Map ? _int(decoded['unread_count']) : 0;
  }

  static Future<List<Map<String, dynamic>>> getNotifications({int limit = 60}) async {
    final uri = Uri.parse('${ApiClient.baseUrl}/api/connect_notifications.php')
        .replace(queryParameters: {'limit': '$limit'});
    final response = await ApiClient.offlineFirstGet(uri, headers: await ApiClient.getHeaders())
        .timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_error(response, 'Unable to load notifications.'));
    }
    final decoded = _decode(response);
    final raw = decoded is Map ? decoded['data'] : decoded;
    if (raw is! List) return <Map<String, dynamic>>[];
    return raw.whereType<Map>().map((item) {
      final row = _map(item);
      row['id'] = _int(row['id']);
      row['is_read'] = _bool(row['is_read']);
      if (row['post_id'] != null) row['post_id'] = _int(row['post_id']);
      if (row['comment_id'] != null) row['comment_id'] = _int(row['comment_id']);
      if (row['community_id'] != null) row['community_id'] = _int(row['community_id']);
      return row;
    }).toList();
  }

  static Future<void> markAllNotificationsRead() async {
    final response = await http
        .post(
          Uri.parse('${ApiClient.baseUrl}/api/connect_notifications.php'),
          headers: await ApiClient.getHeaders(),
          body: jsonEncode({'action': 'mark_all_read'}),
        )
        .timeout(const Duration(seconds: 15));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_error(response, 'Unable to update notifications.'));
    }
  }

  static Future<void> markNotificationRead(int notificationId) async {
    if (notificationId <= 0) return;
    final response = await http
        .post(
          Uri.parse('${ApiClient.baseUrl}/api/connect_notifications.php'),
          headers: await ApiClient.getHeaders(),
          body: jsonEncode({
            'action': 'mark_read',
            'notification_id': notificationId,
          }),
        )
        .timeout(const Duration(seconds: 15));
    await ApiClient.handleUnauthorized(response);
  }

  static Future<List<Map<String, dynamic>>> getCommunities({String search = ''}) async {
    final uri = Uri.parse('${ApiClient.baseUrl}/api/connect_communities.php').replace(
      queryParameters: {if (search.trim().isNotEmpty) 'q': search.trim()},
    );
    final response = await ApiClient.offlineFirstGet(uri, headers: await ApiClient.getHeaders())
        .timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_error(response, 'Unable to load communities.'));
    }
    final decoded = _decode(response);
    final raw = decoded is Map ? decoded['data'] : decoded;
    if (raw is! List) return <Map<String, dynamic>>[];
    return raw.whereType<Map>().map((item) {
      final row = _map(item);
      row['id'] = _int(row['id']);
      row['members_count'] = _int(row['members_count']);
      row['is_member'] = _bool(row['is_member']);
      return row;
    }).toList();
  }

  static Future<Map<String, dynamic>> createCommunity({
    required String name,
    required String description,
  }) async {
    final response = await http
        .post(
          Uri.parse('${ApiClient.baseUrl}/api/connect_communities.php'),
          headers: await ApiClient.getHeaders(),
          body: jsonEncode({
            'name': name.trim(),
            'description': description.trim(),
          }),
        )
        .timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200 && response.statusCode != 201) {
      throw Exception(_error(response, 'Unable to create the community.'));
    }
    final decoded = _decode(response);
    if (decoded is Map && decoded['data'] is Map) return _map(decoded['data']);
    return <String, dynamic>{};
  }

  static Future<Map<String, dynamic>> updateMembership({
    required int communityId,
    required bool join,
  }) async {
    final response = await http
        .post(
          Uri.parse('${ApiClient.baseUrl}/api/connect_community_members.php'),
          headers: await ApiClient.getHeaders(),
          body: jsonEncode({
            'community_id': communityId,
            'action': join ? 'join' : 'leave',
          }),
        )
        .timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_error(response, 'Unable to update community membership.'));
    }
    return _map(_decode(response));
  }

  static Future<List<Map<String, dynamic>>> getCommunityMembers(int communityId) async {
    final uri = Uri.parse('${ApiClient.baseUrl}/api/connect_community_members.php')
        .replace(queryParameters: {'community_id': '$communityId'});
    final response = await ApiClient.offlineFirstGet(uri, headers: await ApiClient.getHeaders())
        .timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_error(response, 'Unable to load community members.'));
    }
    final decoded = _decode(response);
    final raw = decoded is Map ? decoded['data'] : decoded;
    if (raw is! List) return <Map<String, dynamic>>[];
    return raw.whereType<Map>().map(_map).toList();
  }
}
