import 'dart:convert';
import 'dart:typed_data';

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

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

class CampusEventMedia {
  final int id;
  final int eventId;
  final String type;
  final String path;
  final String thumbnailPath;
  final int sizeBytes;

  const CampusEventMedia({
    required this.id,
    required this.eventId,
    required this.type,
    required this.path,
    required this.thumbnailPath,
    required this.sizeBytes,
  });

  bool get isVideo => type.toLowerCase() == 'video';
  bool get isImage => !isVideo;

  factory CampusEventMedia.fromJson(Map<String, dynamic> json) {
    return CampusEventMedia(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      eventId: int.tryParse('${json['event_id'] ?? 0}') ?? 0,
      type: '${json['type'] ?? json['media_type'] ?? 'image'}',
      path: '${json['path'] ?? json['media_path'] ?? ''}',
      thumbnailPath: '${json['thumbnail_path'] ?? json['thumbnail'] ?? ''}',
      sizeBytes: int.tryParse('${json['size_bytes'] ?? 0}') ?? 0,
    );
  }
}

class CampusEvent {
  final int id;
  final int authorId;
  final String title;
  final String description;
  final String category;
  final String campus;
  final String location;
  final String speakers;
  final String status;
  final bool isActive;
  final DateTime eventDate;
  final DateTime createdAt;
  final DateTime? updatedAt;
  final String authorName;
  final String authorRole;
  final String authorProfilePicture;
  final String legacyImageUrl;
  final List<CampusEventMedia> media;
  final int likeCount;
  final int commentCount;
  final bool likedByMe;

  const CampusEvent({
    required this.id,
    required this.authorId,
    required this.title,
    required this.description,
    required this.category,
    required this.campus,
    required this.location,
    required this.speakers,
    required this.status,
    required this.isActive,
    required this.eventDate,
    required this.createdAt,
    required this.updatedAt,
    required this.authorName,
    required this.authorRole,
    required this.authorProfilePicture,
    required this.legacyImageUrl,
    required this.media,
    required this.likeCount,
    required this.commentCount,
    required this.likedByMe,
  });

  List<CampusEventMedia> get images => media.where((item) => item.isImage).toList();
  CampusEventMedia? get video {
    for (final item in media) {
      if (item.isVideo) return item;
    }
    return null;
  }

  factory CampusEvent.fromJson(Map<String, dynamic> json) {
    final media = <CampusEventMedia>[];
    final rawMedia = json['media'];
    if (rawMedia is List) {
      for (final item in rawMedia) {
        if (item is Map) {
          media.add(CampusEventMedia.fromJson(
            item.map((key, value) => MapEntry(key.toString(), value)),
          ));
        }
      }
    }

    return CampusEvent(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      authorId: int.tryParse('${json['author_id'] ?? 0}') ?? 0,
      title: '${json['title'] ?? 'Untitled Event'}',
      description: '${json['description'] ?? ''}',
      category: '${json['category'] ?? 'General'}',
      campus: '${json['campus'] ?? ''}',
      location: '${json['location'] ?? ''}',
      speakers: '${json['speakers'] ?? ''}',
      status: '${json['status'] ?? 'Published'}',
      isActive: _bool(json['is_active'] ?? true),
      eventDate: DateTime.tryParse('${json['event_date'] ?? ''}') ?? DateTime.now(),
      createdAt: DateTime.tryParse('${json['created_at'] ?? ''}') ?? DateTime.now(),
      updatedAt: DateTime.tryParse('${json['updated_at'] ?? ''}'),
      authorName: '${json['author_name'] ?? 'Rockview Events'}',
      authorRole: '${json['author_role'] ?? 'staff'}',
      authorProfilePicture: '${json['author_profile_picture'] ?? ''}',
      legacyImageUrl: '${json['image_url'] ?? ''}',
      media: media,
      likeCount: int.tryParse('${json['like_count'] ?? 0}') ?? 0,
      commentCount: int.tryParse('${json['comment_count'] ?? 0}') ?? 0,
      likedByMe: _bool(json['liked_by_me']),
    );
  }

  CampusEvent copyWith({
    int? likeCount,
    int? commentCount,
    bool? likedByMe,
  }) {
    return CampusEvent(
      id: id,
      authorId: authorId,
      title: title,
      description: description,
      category: category,
      campus: campus,
      location: location,
      speakers: speakers,
      status: status,
      isActive: isActive,
      eventDate: eventDate,
      createdAt: createdAt,
      updatedAt: updatedAt,
      authorName: authorName,
      authorRole: authorRole,
      authorProfilePicture: authorProfilePicture,
      legacyImageUrl: legacyImageUrl,
      media: media,
      likeCount: likeCount ?? this.likeCount,
      commentCount: commentCount ?? this.commentCount,
      likedByMe: likedByMe ?? this.likedByMe,
    );
  }
}

class CampusEventComment {
  final int id;
  final int eventId;
  final int userId;
  final int? parentCommentId;
  final String comment;
  final String authorName;
  final String authorRole;
  final String authorProfilePicture;
  final DateTime createdAt;

  const CampusEventComment({
    required this.id,
    required this.eventId,
    required this.userId,
    required this.parentCommentId,
    required this.comment,
    required this.authorName,
    required this.authorRole,
    required this.authorProfilePicture,
    required this.createdAt,
  });

  bool get isReply => parentCommentId != null;

  factory CampusEventComment.fromJson(Map<String, dynamic> json) {
    return CampusEventComment(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      eventId: int.tryParse('${json['event_id'] ?? 0}') ?? 0,
      userId: int.tryParse('${json['user_id'] ?? 0}') ?? 0,
      parentCommentId: int.tryParse('${json['parent_comment_id'] ?? ''}'),
      comment: '${json['comment'] ?? ''}',
      authorName: '${json['author_name'] ?? 'Rockview User'}',
      authorRole: '${json['author_role'] ?? 'user'}',
      authorProfilePicture: '${json['author_profile_picture'] ?? ''}',
      createdAt: DateTime.tryParse('${json['created_at'] ?? ''}') ?? DateTime.now(),
    );
  }
}

class EventMentionableUser {
  final int id;
  final String fullName;
  final String role;
  final String campus;
  final String profilePicture;

  const EventMentionableUser({
    required this.id,
    required this.fullName,
    required this.role,
    required this.campus,
    required this.profilePicture,
  });

  factory EventMentionableUser.fromJson(Map<String, dynamic> json) {
    return EventMentionableUser(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      fullName: '${json['full_name'] ?? 'Rockview User'}',
      role: '${json['role'] ?? 'user'}',
      campus: '${json['campus'] ?? ''}',
      profilePicture: '${json['profile_picture'] ?? ''}',
    );
  }
}

class CampusEventNotification {
  final int id;
  final int? eventId;
  final int? commentId;
  final String type;
  final String title;
  final String message;
  final String actorName;
  final String actorProfilePicture;
  final bool isRead;
  final DateTime createdAt;

  const CampusEventNotification({
    required this.id,
    required this.eventId,
    required this.commentId,
    required this.type,
    required this.title,
    required this.message,
    required this.actorName,
    required this.actorProfilePicture,
    required this.isRead,
    required this.createdAt,
  });

  factory CampusEventNotification.fromJson(Map<String, dynamic> json) {
    return CampusEventNotification(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      eventId: int.tryParse('${json['event_id'] ?? ''}'),
      commentId: int.tryParse('${json['comment_id'] ?? ''}'),
      type: '${json['type'] ?? 'general'}',
      title: '${json['title'] ?? 'Event notification'}',
      message: '${json['message'] ?? ''}',
      actorName: '${json['actor_name'] ?? ''}',
      actorProfilePicture: '${json['actor_profile_picture'] ?? ''}',
      isRead: _bool(json['is_read']),
      createdAt: DateTime.tryParse('${json['created_at'] ?? ''}') ?? DateTime.now(),
    );
  }
}

class CampusEventPage {
  final List<CampusEvent> events;
  final bool hasMore;
  final int total;

  const CampusEventPage({required this.events, required this.hasMore, required this.total});
}

class CampusEventNotificationPage {
  final List<CampusEventNotification> items;
  final int unreadCount;

  const CampusEventNotificationPage({required this.items, required this.unreadCount});
}

class CampusEventsService {
  static const List<String> categories = <String>[
    'Academic',
    'Workshop',
    'Seminar',
    'Conference',
    'Sports',
    'Student Life',
    'Community',
    'Career',
    'Ceremony',
    'General',
  ];

  static bool isStoredMediaPath(String value) {
    final normalized = value.trim().replaceAll('\\', '/');
    return normalized.startsWith('uploads/') || normalized.startsWith('/uploads/');
  }

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

  static Future<Map<String, dynamic>> getCurrentUser() async {
    final response = await ApiClient.offlineFirstGet(
      Uri.parse('${ApiClient.baseUrl}/api/users.php/me'),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 15));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to identify the signed-in account.'));
    }
    final decoded = _decode(response);
    if (decoded is Map) return decoded.map((key, value) => MapEntry(key.toString(), value));
    throw const FormatException('Current-user endpoint returned invalid data.');
  }

  static Future<List<String>> getCampuses() async {
    for (final url in <String>[
      '${ApiClient.baseUrl}/api/campuses.php',
      '${ApiClient.baseUrl}/campuses',
    ]) {
      try {
        final response = await ApiClient.offlineFirstGet(
          Uri.parse(url),
          headers: await ApiClient.getHeaders(),
        ).timeout(const Duration(seconds: 12));
        if (response.statusCode != 200) continue;
        final decoded = _decode(response);
        final rows = decoded is Map ? decoded['data'] ?? decoded['campuses'] : decoded;
        if (rows is! List) continue;
        final names = <String>{};
        for (final item in rows) {
          if (item is Map) {
            final name = '${item['name'] ?? item['campus_name'] ?? ''}'.trim();
            if (name.isNotEmpty) names.add(name);
          }
        }
        final result = names.toList()..sort();
        return result;
      } catch (_) {}
    }
    return const <String>[];
  }

  static Future<CampusEventPage> getEvents({
    String scope = 'upcoming',
    String? campus,
    String? search,
    int page = 1,
    int limit = 8,
    bool refresh = false,
  }) async {
    final params = <String, String>{
      'scope': scope,
      'page': '$page',
      'limit': '$limit',
    };
    if (campus != null && campus.trim().isNotEmpty && campus != 'All Campuses') {
      params['campus'] = campus.trim();
    }
    if (search != null && search.trim().isNotEmpty) params['q'] = search.trim();

    final response = await ApiClient.offlineFirstGet(
      Uri.parse('${ApiClient.baseUrl}/api/events_feed.php').replace(queryParameters: params),
      headers: await ApiClient.getHeaders(),
      forceRefresh: refresh,
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to load campus events.'));
    }

    final decoded = _decode(response);
    final rows = decoded is Map ? decoded['data'] ?? const [] : decoded;
    if (rows is! List) throw const FormatException('Events endpoint returned invalid data.');
    final events = rows
        .whereType<Map>()
        .map((item) => CampusEvent.fromJson(item.map((key, value) => MapEntry(key.toString(), value))))
        .toList();
    final pagination = decoded is Map && decoded['pagination'] is Map
        ? Map<String, dynamic>.from(decoded['pagination'] as Map)
        : <String, dynamic>{};
    return CampusEventPage(
      events: events,
      hasMore: _bool(pagination['has_more'] ?? (events.length >= limit)),
      total: int.tryParse('${pagination['total'] ?? events.length}') ?? events.length,
    );
  }

  static Future<int> createEvent({
    required String title,
    required String description,
    required String category,
    required DateTime eventDate,
    required String location,
    required String speakers,
  }) async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/events_feed.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode(<String, dynamic>{
        'title': title.trim(),
        'description': description.trim(),
        'category': category.trim(),
        'event_date': eventDate.toUtc().toIso8601String(),
        'location': location.trim(),
        'speakers': speakers.trim(),
        'status': 'Published',
        'is_active': true,
      }),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 201 && response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to create the event.'));
    }
    final decoded = _decode(response);
    if (decoded is Map) {
      ApiClient.announceSuccessfulMutation(Uri.parse('${ApiClient.baseUrl}/api/events_feed.php'));
      return int.tryParse('${decoded['id'] ?? 0}') ?? 0;
    }
    throw const FormatException('Create-event endpoint returned invalid data.');
  }

  static Future<void> updateEvent(int id, Map<String, dynamic> changes) async {
    final response = await http.put(
      Uri.parse('${ApiClient.baseUrl}/api/events_feed.php?id=$id'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode(changes),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to update the event.'));
    }
    ApiClient.announceSuccessfulMutation(Uri.parse('${ApiClient.baseUrl}/api/events_feed.php'));
  }

  static Future<void> deleteEvent(int id) async {
    final response = await http.delete(
      Uri.parse('${ApiClient.baseUrl}/api/events_feed.php?id=$id'),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to delete the event.'));
    }
    ApiClient.announceSuccessfulMutation(Uri.parse('${ApiClient.baseUrl}/api/events_feed.php'));
  }

  static Future<List<CampusEventMedia>> uploadImages(int eventId, List<XFile> files) async {
    if (files.isEmpty) return const <CampusEventMedia>[];
    final request = http.MultipartRequest('POST', Uri.parse('${ApiClient.baseUrl}/api/event_media.php'));
    final headers = await ApiClient.getHeaders();
    headers.remove('Content-Type');
    request.headers.addAll(headers);
    request.fields['event_id'] = '$eventId';
    request.fields['media_type'] = 'image';
    for (final file in files) {
      final bytes = await file.readAsBytes();
      request.files.add(http.MultipartFile.fromBytes('images[]', bytes, filename: file.name));
    }
    final streamed = await request.send().timeout(const Duration(seconds: 60));
    final response = await http.Response.fromStream(streamed);
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 201 && response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to upload event pictures.'));
    }
    final decoded = _decode(response);
    final rows = decoded is Map ? decoded['data'] ?? const [] : const [];
    if (rows is! List) return const <CampusEventMedia>[];
    return rows.whereType<Map>().map((item) => CampusEventMedia.fromJson(
      item.map((key, value) => MapEntry(key.toString(), value)),
    )).toList();
  }

  static Future<CampusEventMedia?> uploadVideo(int eventId, XFile file) async {
    final length = await file.length();
    if (length > 10 * 1024 * 1024) {
      throw Exception('Event video must not exceed 10 MB.');
    }
    final request = http.MultipartRequest('POST', Uri.parse('${ApiClient.baseUrl}/api/event_media.php'));
    final headers = await ApiClient.getHeaders();
    headers.remove('Content-Type');
    request.headers.addAll(headers);
    request.fields['event_id'] = '$eventId';
    request.fields['media_type'] = 'video';
    final bytes = await file.readAsBytes();
    request.files.add(http.MultipartFile.fromBytes('video', bytes, filename: file.name));
    final streamed = await request.send().timeout(const Duration(seconds: 90));
    final response = await http.Response.fromStream(streamed);
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 201 && response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to upload event video.'));
    }
    final decoded = _decode(response);
    dynamic payload = decoded;
    if (decoded is Map) payload = decoded['data'] ?? decoded['media'];
    if (payload is Map) {
      return CampusEventMedia.fromJson(payload.map((key, value) => MapEntry(key.toString(), value)));
    }
    return null;
  }

  static Future<void> deleteMedia(int mediaId) async {
    final response = await http.delete(
      Uri.parse('${ApiClient.baseUrl}/api/event_media.php?id=$mediaId'),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to remove event media.'));
    }
  }

  static Future<Map<String, dynamic>> toggleLike(int eventId) async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/event_likes.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode(<String, dynamic>{'event_id': eventId}),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to update event like.'));
    }
    final decoded = _decode(response);
    return decoded is Map ? decoded.map((key, value) => MapEntry(key.toString(), value)) : <String, dynamic>{};
  }

  static Future<List<CampusEventComment>> getComments(int eventId) async {
    final response = await ApiClient.offlineFirstGet(
      Uri.parse('${ApiClient.baseUrl}/api/event_comments.php?event_id=$eventId'),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to load event comments.'));
    }
    final decoded = _decode(response);
    final rows = decoded is Map ? decoded['data'] ?? const [] : decoded;
    if (rows is! List) return const <CampusEventComment>[];
    return rows.whereType<Map>().map((item) => CampusEventComment.fromJson(
      item.map((key, value) => MapEntry(key.toString(), value)),
    )).toList();
  }

  static Future<CampusEventComment> addComment(
    int eventId,
    String comment, {
    int? parentCommentId,
    List<int> mentionUserIds = const <int>[],
  }) async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/event_comments.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode(<String, dynamic>{
        'event_id': eventId,
        'comment': comment.trim(),
        if (parentCommentId != null) 'parent_comment_id': parentCommentId,
        if (mentionUserIds.isNotEmpty) 'mention_user_ids': mentionUserIds,
      }),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 201 && response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to post the event comment.'));
    }
    final decoded = _decode(response);
    dynamic payload = decoded;
    if (decoded is Map) payload = decoded['data'] ?? decoded['comment'] ?? decoded;
    if (payload is! Map) throw const FormatException('Event comment endpoint returned invalid data.');
    return CampusEventComment.fromJson(payload.map((key, value) => MapEntry(key.toString(), value)));
  }

  static Future<List<EventMentionableUser>> getMentionableUsers(int eventId) async {
    final response = await ApiClient.offlineFirstGet(
      Uri.parse('${ApiClient.baseUrl}/api/event_mentions.php?event_id=$eventId'),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) return const <EventMentionableUser>[];
    final decoded = _decode(response);
    final rows = decoded is Map ? decoded['data'] ?? const [] : decoded;
    if (rows is! List) return const <EventMentionableUser>[];
    return rows.whereType<Map>().map((item) => EventMentionableUser.fromJson(
      item.map((key, value) => MapEntry(key.toString(), value)),
    )).toList();
  }

  static Future<CampusEventNotificationPage> getNotifications({int limit = 30}) async {
    final response = await ApiClient.offlineFirstGet(
      Uri.parse('${ApiClient.baseUrl}/api/event_notifications.php?limit=$limit'),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to load event notifications.'));
    }
    final decoded = _decode(response);
    final rows = decoded is Map ? decoded['data'] ?? const [] : const [];
    final items = rows is List
        ? rows.whereType<Map>().map((item) => CampusEventNotification.fromJson(
              item.map((key, value) => MapEntry(key.toString(), value)),
            )).toList()
        : <CampusEventNotification>[];
    return CampusEventNotificationPage(
      items: items,
      unreadCount: decoded is Map ? int.tryParse('${decoded['unread_count'] ?? 0}') ?? 0 : 0,
    );
  }

  static Future<void> markNotificationRead(int id) async {
    final response = await http.put(
      Uri.parse('${ApiClient.baseUrl}/api/event_notifications.php?id=$id'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode(<String, dynamic>{'is_read': true}),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
  }

  static Future<void> markAllNotificationsRead() async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/event_notifications.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode(<String, dynamic>{'action': 'mark_all_read'}),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
  }
}

dynamic _decode(http.Response response) {
  final body = response.body.trim();
  if (body.isEmpty) return <String, dynamic>{};
  try {
    return jsonDecode(body);
  } catch (_) {
    throw FormatException('Server returned invalid JSON: $body');
  }
}

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

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