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

import 'package:dio/dio.dart';
import 'package:hamlemuhcrm/features/message/model/page_key_response.dart';
import 'package:hamlemuhcrm/features/message/model/upload_file.dart';

import '../../core/base/base_response.dart';
import '../../core/constants/url_services_constant.dart';
import '../../core/extensions/log_extension.dart';
import '../../core/init/network/network_manager.dart';
import '../../features/message/model/group_latest_message.dart';
import '../../features/message/model/group_one_on_one_response.dart';
import '../../features/message/model/group_response.dart';
import '../../features/message/model/message.dart';
import '../../features/message/model/message_response.dart';
import '../../features/message/model/query/req_fetch_group.dart';
import '../../features/message/model/query/req_fetch_message.dart';
import '../../features/message/model/query/req_multi_group.dart';
import '../../features/message/model/query/req_one_on_one_group.dart';
import '../../features/message/model/query/req_page_key.dart';
import '../../features/message/model/query/req_seen_update_group.dart';
import '../../features/message/model/query/req_send_message.dart';
import '../../features/message/model/query/req_update_group.dart';
import '../../features/message/model/query/req_upload_file.dart';

class MessageRepository {
  final Dio dio = NetworkManager.instance.dio;

  /// Normal grup listeleme metodu
  Future<GroupResponse?> fetchGroupList(ReqFetchGroup model) async {
    try {
      var url = URLAPIService.instance.grupListeleURL;
      final response =
          await dio.post(url, data: FormData.fromMap(model.toJson()));
      final responseData = jsonDecode(response.data);
      final gundemlerResponse = GroupResponse.fromJson(responseData);

      return gundemlerResponse;
    } catch (error) {
      // Hata durumunda fake model dondurelım // success 0 olması önemli
      return GroupResponse(
          message: "hata olustu",
          digerGorusulmeyenler: [],
          firmaGorusulmeyenler: [],
          gorusulenler: [],
          success: 0);
    }
  }

  /// - Compute ile çoklu çekirdek kullanımı için static bir metot oluşturmak durumundayız

  static Future<GroupResponse> fetchComputeGroupList(
      ReqFetchGroup model) async {
    try {
      var url =
          '${URLAPIService.baseURL}${URLAPIService.instance.grupListeleURL}';
      final response =
          await Dio().post(url, data: FormData.fromMap(model.toJson()));
      final responseData = jsonDecode(response.data);
      final gundemlerResponse = GroupResponse.fromJson(responseData);

      return gundemlerResponse;
    } catch (_) {
      // Hata durumunda fake model dondurelım // success 0 olması önemli
      return GroupResponse(
          message: "hata olustu",
          digerGorusulmeyenler: [],
          firmaGorusulmeyenler: [],
          gorusulenler: [],
          success: 0);
    }
  }

  /// Tüm mesajları listeleme metodu
  Future<List<Message>> fetchMessageList(ReqFetchMessage model) async {
    try {
      var url = URLAPIService.instance.mesajListeleURL;
      final response =
          await dio.post(url, data: FormData.fromMap(model.toJson()));
      final responseData = jsonDecode(response.data);
      final mesajlarResponse = MessageResponse.fromJson(responseData);
      return mesajlarResponse.mesaj ?? [];
    } catch (error) {
      // Hata durumunda boş bir liste döndürelim
      return [];
    }
  }

  /// Sayfalama şeklinde mesajları listeleme metodu
  Future<List<Message>> fetchPaginationMessageList(ReqFetchMessage model,
      [String lastId = "-1"]) async {
    try {
      var url = URLAPIService.instance.mesajPaginationListelemeURL;
      final response = await dio.get(url, queryParameters: <String, dynamic>{
        "token": model.token,
        "loginuserid": model.loginuserid,
        "userfirmid": model.userfirmid,
        "grupid": model.grupId,
        "enustmesajid": lastId,
        "limit": 10
      });

      if (response.statusCode == 200) {
        final responseData = jsonDecode(response.data);
        final mesajlarResponse = MessageResponse.fromJson(responseData);
        return mesajlarResponse.mesaj ?? [];
      } else {
        return [];
      }
    } catch (_) {
      return [];
    }
  }

  /// - send for service for initial state bottomid value -1 => [] lempty list
  Future<List<Message>> fetchLastMessageList(
      ReqFetchMessage model, String bottomid) async {
    try {
      var url = URLAPIService.instance.sonMesajlariListelemeURL;
      final response = await dio.get(url, queryParameters: <String, dynamic>{
        "token": model.token,
        "loginuserid": model.loginuserid,
        "userfirmid": model.userfirmid,
        "grupid": model.grupId,
        "bottomid": bottomid,
      });

      if (response.statusCode == 200) {
        final responseData = jsonDecode(response.data);
        final mesajlarResponse = MessageResponse.fromJson(responseData);
        return mesajlarResponse.mesaj ?? [];
      } else {
        return [];
      }
    } catch (_) {
      return [];
    }
  }

  /// - Gruba girildiğinde o gruba ait son hareketi güncelleme metodu
  Future<void> lastSeenUpdate(ReqSeenUpdateGroup model) async {
    try {
      var url = URLAPIService.instance.grupSonGorulmeGuncelleURL;
      final response =
          await dio.post(url, data: FormData.fromMap(model.toJson()));
      'son hareket guncelleme state : ${response.data}'.log();
    } catch (error) {
      'son hareket guncelleme state : $error'.log();
    }
  }

  Future<GroupCreateResponse> createOneOnOneGroup(
      ReqOneOnOneGroup model) async {
    try {
      var url = URLAPIService.instance.birebirGrupOlusturURL;
      final response =
          await dio.post(url, data: FormData.fromMap(model.toJson()));

      if (response.statusCode == HttpStatus.ok) {
        // JSON string'i Map'e çevir
        Map<String, dynamic> responseData = json.decode(response.data);

        'donen grup : $responseData'.log();

        if (responseData['success'] == 1) {
          return GroupCreateResponse.fromJson(responseData);
        } else {
          return GroupCreateResponse(
            success: 0,
            grup: GroupLatestMessage(),
            message: "Başarısız işlem veya hatalı JSON formatı",
          );
        }
      } else {
        return GroupCreateResponse(
          success: 0,
          grup: GroupLatestMessage(),
          message: "HTTP Hatası: ${response.statusCode}",
        );
      }
    } catch (e) {
      throw Exception('Yeni grup oluşturulamadı - Exception');
    }
  }

  Future<GroupCreateResponse> createMultiGroup(ReqMultiGroup model) async {
    try {
      var url = URLAPIService.instance.cokluGrupOlusturURL;
      final response =
          await dio.post(url, data: FormData.fromMap(model.toJson()));

      if (response.statusCode == HttpStatus.ok) {
        // JSON string'i Map'e çevir
        Map<String, dynamic> responseData = json.decode(response.data);

        'donen grup : $responseData'.log();

        if (responseData['success'] == 1) {
          return GroupCreateResponse.fromJson(responseData);
        } else {
          return GroupCreateResponse(
            success: 0,
            grup: GroupLatestMessage(),
            message: "Başarısız işlem veya hatalı JSON formatı",
          );
        }
      } else {
        return GroupCreateResponse(
          success: 0,
          grup: GroupLatestMessage(),
          message: "HTTP Hatası: ${response.statusCode}",
        );
      }
    } catch (e) {
      throw Exception('Yeni grup oluşturulamadı - Exception');
    }
  }

  Future<BaseResponseModel> updateMultiGroup(ReqUpdateGroup model) async {
    try {
      var url = URLAPIService.instance.grupGuncelleURL;
      final response =
          await dio.post(url, data: FormData.fromMap(model.toJson()));

      if (response.statusCode == HttpStatus.ok) {
        if (response.data is String) {
          final Map<String, dynamic> responseData = json.decode(response.data);
          return BaseResponseModel.fromJson(responseData);
        } else if (response.data is Map<String, dynamic>) {
          return BaseResponseModel.fromJson(response.data);
        } else {
          return BaseResponseModel(
            success: 0,
            message: "Başarısız işlem veya hatalı JSON formatı",
          );
        }
      } else {
        return BaseResponseModel(
          success: 0,
          message: "HTTP Hatası: ${response.statusCode}",
        );
      }
    } catch (e) {
      throw Exception('Grup Güncellenemedi - Exception');
    }
  }

  Future<BaseResponseModel?> sendMessageToGroup(ReqSendMessage model) async {
    try {
      var url = URLAPIService.instance.grubaMesajGonderURL;
      final response =
          await dio.post(url, data: FormData.fromMap(model.toJson()));

      if (response.statusCode == 200) {
        final Map<String, dynamic> responseMap = response.data is String
            ? json.decode(response.data)
            : response.data;
        return BaseResponseModel.fromJson(responseMap);
      } else {
        return BaseResponseModel(message: 'İşlem başarısız', success: 0);
      }
    } catch (e) {
      'Hata yakalandı: $e'.log();
      return BaseResponseModel(message: 'Hata Oluştu', success: 0);
    }
  }

  Future<String> uploadFileToServer(ReqUploadFile model) async {
    try {
      var url = URLAPIService.instance.fileUploadURL;

      final FormData data = FormData.fromMap({
        "loginuserid": model.loginuserid,
        "messagefile": await MultipartFile.fromFile(model.filePath,
            filename: model.fileName),
      });

      final response = await dio.post(
        url,
        data: data,
        onSendProgress: (count, total) {
          'upload ${model.fileName} .. : $count $total'.log();
        },
      );
      if (response.statusCode == 200) {
        'result file : ${response.data}'.log();

        if (response.data is Map<String, dynamic>?) {
          'return response : ${UploadFile.fromJson(response.data).mesajformat}'
              .log();
          return UploadFile.fromJson(response.data).mesajformat ?? '';
        }
      }
      return '';
    } catch (_) {
      throw Exception('${model.fileName} dosya yüklenemedi');
    }
  }

  Future<PageKeyResponse> callPageKeyService(ReqPageKey model) async {
    final url =
        '${URLAPIService.instance.messageWebViewBaseURL}pagekey_run.php';
    final response =
        await dio.post(url, data: FormData.fromMap(model.toJson()));

    if (response.statusCode == 200) {
      return PageKeyResponse.fromJson(json.decode(response.data));
    }
    'test page key ${response.data}'.log();
    return PageKeyResponse(pagekey: 'null',pagestatuse: 'false');
  }
}
