import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logger/logger.dart';
import 'package:real_estate_mobile/core/constants/api_constants.dart';
import 'package:real_estate_mobile/core/network/api_client.dart';
import 'package:real_estate_mobile/core/network/api_exceptions.dart';
import 'package:real_estate_mobile/features/support_chat/data/models/support_chat_models.dart';

final _log = Logger(printer: PrettyPrinter(methodCount: 0));

class SupportChatRepository {
  final Dio _dio = ApiClient.instance.dio;

  /// POST /support-chat — get or create a support chat
  Future<SupportChat> getOrCreateChat() async {
    try {
      final response = await _dio.post(ApiConstants.supportChat);
      return SupportChat.fromJson(
          response.data['data'] as Map<String, dynamic>);
    } on DioException catch (e) {
      if (e.error is ApiException) throw e.error as ApiException;
      throw ApiException(
        message: e.message ?? 'Failed to create support chat',
        statusCode: e.response?.statusCode,
      );
    }
  }

  /// GET /support-chat/my — get user's existing chat
  Future<SupportChat> getMyChat() async {
    try {
      final response = await _dio.get('${ApiConstants.supportChat}/my');
      return SupportChat.fromJson(
          response.data['data'] as Map<String, dynamic>);
    } on DioException catch (e) {
      if (e.error is ApiException) throw e.error as ApiException;
      throw ApiException(
        message: e.message ?? 'Failed to fetch support chat',
        statusCode: e.response?.statusCode,
      );
    }
  }

  /// GET /support-chat/:chatId/messages
  Future<({List<SupportMessage> messages, SupportPagination pagination})>
      getMessages(String chatId, {int page = 1, int limit = 50}) async {
    try {
      final response = await _dio.get(
        '${ApiConstants.supportChat}/$chatId/messages',
        queryParameters: {'page': page, 'limit': limit},
      );
      final data = response.data['data'] as Map<String, dynamic>;
      final messages = (data['messages'] as List<dynamic>)
          .map((e) => SupportMessage.fromJson(e as Map<String, dynamic>))
          .toList();
      final pagination = SupportPagination.fromJson(
          data['pagination'] as Map<String, dynamic>);
      return (messages: messages, pagination: pagination);
    } on DioException catch (e) {
      if (e.error is ApiException) throw e.error as ApiException;
      throw ApiException(
        message: e.message ?? 'Failed to fetch messages',
        statusCode: e.response?.statusCode,
      );
    }
  }

  /// POST /support-chat/:chatId/messages
  Future<SupportMessage> sendMessage(String chatId, String content) async {
    try {
      final response = await _dio.post(
        '${ApiConstants.supportChat}/$chatId/messages',
        data: {'content': content},
      );
      return SupportMessage.fromJson(
          response.data['data'] as Map<String, dynamic>);
    } on DioException catch (e) {
      if (e.error is ApiException) throw e.error as ApiException;
      throw ApiException(
        message: e.message ?? 'Failed to send message',
        statusCode: e.response?.statusCode,
      );
    }
  }

  /// PATCH /support-chat/:chatId/read
  Future<void> markAsRead(String chatId) async {
    try {
      await _dio.patch('${ApiConstants.supportChat}/$chatId/read');
    } on DioException catch (e) {
      _log.w('Failed to mark support chat as read: ${e.message}');
    }
  }
}

final supportChatRepositoryProvider = Provider<SupportChatRepository>((ref) {
  return SupportChatRepository();
});
