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

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

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

class SupportAttachment {
  final int id;
  final int messageId;
  final String mediaType;
  final String path;
  final String thumbnailPath;
  final String originalName;
  final String mimeType;
  final int sizeBytes;

  const SupportAttachment({
    required this.id,
    required this.messageId,
    required this.mediaType,
    required this.path,
    required this.thumbnailPath,
    required this.originalName,
    required this.mimeType,
    required this.sizeBytes,
  });

  bool get isImage => mediaType.toLowerCase() == 'image';
  bool get isDocument => !isImage;

  factory SupportAttachment.fromJson(Map<String, dynamic> json) {
    return SupportAttachment(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      messageId: int.tryParse('${json['message_id'] ?? 0}') ?? 0,
      mediaType: '${json['media_type'] ?? 'file'}',
      path: '${json['path'] ?? json['file_path'] ?? ''}',
      thumbnailPath: '${json['thumbnail_path'] ?? ''}',
      originalName: '${json['original_name'] ?? 'Attachment'}',
      mimeType: '${json['mime_type'] ?? ''}',
      sizeBytes: int.tryParse('${json['size_bytes'] ?? 0}') ?? 0,
    );
  }
}

class SupportMessage {
  final int id;
  final int threadId;
  final int senderUserId;
  final String senderName;
  final String senderRole;
  final String senderProfilePicture;
  final String body;
  final DateTime createdAt;
  final bool sentByMe;
  final List<SupportAttachment> attachments;

  const SupportMessage({
    required this.id,
    required this.threadId,
    required this.senderUserId,
    required this.senderName,
    required this.senderRole,
    required this.senderProfilePicture,
    required this.body,
    required this.createdAt,
    required this.sentByMe,
    required this.attachments,
  });

  factory SupportMessage.fromJson(Map<String, dynamic> json) {
    final attachments = <SupportAttachment>[];
    final rawAttachments = json['attachments'];
    if (rawAttachments is List) {
      for (final raw in rawAttachments) {
        if (raw is Map) {
          attachments.add(
            SupportAttachment.fromJson(
              raw.map((key, value) => MapEntry(key.toString(), value)),
            ),
          );
        }
      }
    }

    return SupportMessage(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      threadId: int.tryParse('${json['thread_id'] ?? 0}') ?? 0,
      senderUserId: int.tryParse('${json['sender_user_id'] ?? 0}') ?? 0,
      senderName: '${json['sender_name'] ?? 'Rockview User'}',
      senderRole: '${json['sender_role'] ?? 'user'}',
      senderProfilePicture: '${json['sender_profile_picture'] ?? ''}',
      body: '${json['body'] ?? ''}',
      createdAt: DateTime.tryParse('${json['created_at'] ?? ''}') ?? DateTime.now(),
      sentByMe: _bool(json['sent_by_me']),
      attachments: attachments,
    );
  }
}

class SupportThread {
  final int id;
  final int authorId;
  final String authorName;
  final String authorRole;
  final String authorProfilePicture;
  final String title;
  final String category;
  final String priority;
  final String campus;
  final String status;
  final DateTime createdAt;
  final DateTime updatedAt;
  final DateTime? resolvedAt;
  final String lastMessage;
  final String lastSenderName;
  final DateTime? lastMessageAt;
  final int messageCount;
  final int unreadCount;
  final int attachmentCount;

  const SupportThread({
    required this.id,
    required this.authorId,
    required this.authorName,
    required this.authorRole,
    required this.authorProfilePicture,
    required this.title,
    required this.category,
    required this.priority,
    required this.campus,
    required this.status,
    required this.createdAt,
    required this.updatedAt,
    required this.resolvedAt,
    required this.lastMessage,
    required this.lastSenderName,
    required this.lastMessageAt,
    required this.messageCount,
    required this.unreadCount,
    required this.attachmentCount,
  });

  bool get isResolved => status.toLowerCase() == 'resolved';
  bool get waitingForAdmin => status.toLowerCase() == 'waiting_admin';
  bool get waitingForStaff => status.toLowerCase() == 'waiting_staff';

  factory SupportThread.fromJson(Map<String, dynamic> json) {
    return SupportThread(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      authorId: int.tryParse('${json['author_id'] ?? 0}') ?? 0,
      authorName: '${json['author_name'] ?? 'Staff Member'}',
      authorRole: '${json['author_role'] ?? 'staff'}',
      authorProfilePicture: '${json['author_profile_picture'] ?? ''}',
      title: '${json['title'] ?? 'Support request'}',
      category: '${json['category'] ?? 'General'}',
      priority: '${json['priority'] ?? 'Normal'}',
      campus: '${json['campus'] ?? ''}',
      status: '${json['status'] ?? 'waiting_admin'}',
      createdAt: DateTime.tryParse('${json['created_at'] ?? ''}') ?? DateTime.now(),
      updatedAt: DateTime.tryParse('${json['updated_at'] ?? ''}') ?? DateTime.now(),
      resolvedAt: DateTime.tryParse('${json['resolved_at'] ?? ''}'),
      lastMessage: '${json['last_message'] ?? ''}',
      lastSenderName: '${json['last_sender_name'] ?? ''}',
      lastMessageAt: DateTime.tryParse('${json['last_message_at'] ?? ''}'),
      messageCount: int.tryParse('${json['message_count'] ?? 0}') ?? 0,
      unreadCount: int.tryParse('${json['unread_count'] ?? 0}') ?? 0,
      attachmentCount: int.tryParse('${json['attachment_count'] ?? 0}') ?? 0,
    );
  }
}

class SupportThreadPage {
  final List<SupportThread> threads;
  final bool hasMore;
  final int total;
  final int unreadTotal;

  const SupportThreadPage({
    required this.threads,
    required this.hasMore,
    required this.total,
    required this.unreadTotal,
  });
}

class SupportCreateResult {
  final int threadId;
  final int messageId;

  const SupportCreateResult({required this.threadId, required this.messageId});
}

class CampusSupportService {
  static const List<String> categories = <String>[
    'General Support',
    'Human Resources',
    'Finance',
    'ICT Support',
    'Academic Affairs',
    'Procurement',
    'Facilities',
    'Leave & Attendance',
    'Payroll',
    'Other',
  ];

  static const List<String> priorities = <String>[
    'Normal',
    'Important',
    'Urgent',
  ];

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

  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<SupportThreadPage> getThreads({
    String scope = 'open',
    String? search,
    String? status,
    int page = 1,
    int limit = 30,
  }) async {
    final params = <String, String>{
      'scope': scope,
      'page': '$page',
      'limit': '$limit',
    };
    if (search != null && search.trim().isNotEmpty) params['q'] = search.trim();
    if (status != null && status.trim().isNotEmpty && status != 'all') {
      params['status'] = status.trim();
    }

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

    final decoded = _decode(response);
    if (decoded is! Map) {
      throw const FormatException('Support conversations endpoint returned invalid data.');
    }
    final raw = decoded['data'];
    final threads = <SupportThread>[];
    if (raw is List) {
      for (final item in raw) {
        if (item is Map) {
          threads.add(SupportThread.fromJson(
            item.map((key, value) => MapEntry(key.toString(), value)),
          ));
        }
      }
    }

    final pagination = decoded['pagination'] is Map
        ? Map<String, dynamic>.from(decoded['pagination'] as Map)
        : <String, dynamic>{};

    return SupportThreadPage(
      threads: threads,
      hasMore: _bool(pagination['has_more']),
      total: int.tryParse('${pagination['total'] ?? threads.length}') ?? threads.length,
      unreadTotal: int.tryParse('${decoded['unread_total'] ?? 0}') ?? 0,
    );
  }

  static Future<SupportThread> getThread(int threadId) async {
    final response = await ApiClient.offlineFirstGet(
      Uri.parse('${ApiClient.baseUrl}/api/support_threads.php?id=$threadId'),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 15));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to load the support conversation.'));
    }
    final decoded = _decode(response);
    dynamic payload = decoded;
    if (decoded is Map && decoded['data'] is Map) payload = decoded['data'];
    if (payload is Map) {
      return SupportThread.fromJson(
        payload.map((key, value) => MapEntry(key.toString(), value)),
      );
    }
    throw const FormatException('Support conversation returned invalid data.');
  }

  static Future<SupportCreateResult> createThread({
    required String title,
    required String category,
    required String priority,
    required String body,
  }) async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/support_threads.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode(<String, dynamic>{
        'title': title.trim(),
        'category': category.trim(),
        'priority': priority.trim(),
        'body': body.trim(),
      }),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 201 && response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to submit the question.'));
    }
    final decoded = _decode(response);
    if (decoded is Map) {
      return SupportCreateResult(
        threadId: int.tryParse('${decoded['thread_id'] ?? decoded['id'] ?? 0}') ?? 0,
        messageId: int.tryParse('${decoded['message_id'] ?? 0}') ?? 0,
      );
    }
    throw const FormatException('Create-question endpoint returned invalid data.');
  }

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

  static Future<SupportMessage> sendMessage(int threadId, String body) async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/support_messages.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode(<String, dynamic>{
        'thread_id': threadId,
        'body': body.trim(),
      }),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 201 && response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to send the reply.'));
    }
    final decoded = _decode(response);
    dynamic payload = decoded;
    if (decoded is Map && decoded['data'] is Map) payload = decoded['data'];
    if (payload is Map) {
      return SupportMessage.fromJson(
        payload.map((key, value) => MapEntry(key.toString(), value)),
      );
    }
    throw const FormatException('Reply endpoint returned invalid data.');
  }

  static Future<List<SupportAttachment>> uploadAttachments({
  required int messageId,
  List<XFile> images = const <XFile>[],
  List<PlatformFile> documents = const <PlatformFile>[],
}) async {
  if (images.isEmpty && documents.isEmpty) {
    return const <SupportAttachment>[];
  }

  if (images.length + documents.length > 5) {
    throw Exception(
      'A message can contain at most 5 attachments.',
    );
  }

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

  final headers = await ApiClient.getHeaders();

  // MultipartRequest generates its own multipart Content-Type.
  headers.remove('Content-Type');
  request.headers.addAll(headers);

  request.fields['message_id'] = '$messageId';

  // ============================================================
  // IMAGES
  // ============================================================

  for (final file in images) {
    final bytes = await file.readAsBytes();

    if (bytes.length > 10 * 1024 * 1024) {
      throw Exception(
        '${file.name} is larger than 10 MB.',
      );
    }

    request.files.add(
      http.MultipartFile.fromBytes(
        'images[]',
        bytes,
        filename: file.name,
      ),
    );
  }

  // ============================================================
  // DOCUMENTS
  // ============================================================

  for (final file in documents) {
    final filePath = file.path;

    if (filePath == null || filePath.trim().isEmpty) {
      throw Exception(
        'Unable to access ${file.name}. '
        'Please select the file again.',
      );
    }

    final selectedFile = File(filePath);

    if (!await selectedFile.exists()) {
      throw Exception(
        '${file.name} could not be found on this device.',
      );
    }

    final fileSize = await selectedFile.length();

    if (fileSize > 10 * 1024 * 1024) {
      throw Exception(
        '${file.name} is larger than 10 MB.',
      );
    }

    final bytes = await selectedFile.readAsBytes();

    request.files.add(
      http.MultipartFile.fromBytes(
        'files[]',
        bytes,
        filename: file.name,
      ),
    );
  }

  // ============================================================
  // SEND
  // ============================================================

  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 attachments.',
      ),
    );
  }

  final decoded = _decode(response);

  final raw =
      decoded is Map ? decoded['data'] : null;

  if (raw is! List) {
    return const <SupportAttachment>[];
  }

  return raw
      .whereType<Map>()
      .map(
        (item) => SupportAttachment.fromJson(
          item.map(
            (key, value) =>
                MapEntry(key.toString(), value),
          ),
        ),
      )
      .toList();
}

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

  static dynamic _decode(http.Response response) {
    final body = utf8.decode(response.bodyBytes, allowMalformed: true).trim();
    if (body.isEmpty) return <String, dynamic>{};
    try {
      return jsonDecode(body);
    } catch (_) {
      final startObject = body.indexOf('{');
      final startArray = body.indexOf('[');
      var start = -1;
      if (startObject >= 0 && startArray >= 0) {
        start = startObject < startArray ? startObject : startArray;
      } else if (startObject >= 0) {
        start = startObject;
      } else if (startArray >= 0) {
        start = startArray;
      }
      if (start >= 0) {
        final candidate = body.substring(start);
        try {
          return jsonDecode(candidate);
        } catch (_) {}
      }
      throw FormatException('Server returned non-JSON data: ${body.length > 180 ? '${body.substring(0, 180)}...' : body}');
    }
  }

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

bool _bool(dynamic value) {
  return value == true ||
      value == 1 ||
      value == '1' ||
      '${value ?? ''}'.toLowerCase() == 'true' ||
      '${value ?? ''}'.toLowerCase() == 't';
}
