import 'dart:convert';
import 'package:http/http.dart' as http;
import '/core/constants.dart';
import '/data/models/contact_model.dart';
import '/domain/services/api_service.dart';

class ContactRepository {
  final http.Client _client = http.Client();
  final ApiService _apiService = ApiService();

  Future<List<Contact>> fetchChatContacts() async {
    final token = await _apiService.getAccessToken();
    
    
    DateTime now = DateTime.now();

    Duration offset = now.timeZoneOffset;

    if (token == null) {
      throw Exception('No access token');
    }

    final response = await _client.get(
      Uri.parse('${AppConstants.baseUrl}/users/chats'),
      headers: {
        'Authorization': 'Bearer $token',
        'Content-Type': 'application/json',
      },
    );

    if (response.statusCode == 200) {
      final List<dynamic> data = jsonDecode(utf8.decode(response.bodyBytes));
      print(data);
      List<Contact> contacts = data.map((json) => Contact.fromJson(json)).toList();
      for (var item in contacts) {
        if (item.lastMessageTime != null) {
          DateTime serverTime = item.lastMessageTime!;
          item = item.copyWith(lastMessageTime: serverTime.add(offset));
        }
      }
      return contacts;
    } else {
      throw Exception('Failed to load contacts');
    }
  }

  Future<List<Contact>> fetchAllUsers() async {
    final token = await _apiService.getAccessToken();

    DateTime now = DateTime.now();
    Duration offset = now.timeZoneOffset;
    
    if (token == null) {
      throw Exception('No access token');
    }

    final response = await _client.get(
      Uri.parse('${AppConstants.baseUrl}/users/all'),
      headers: {
        'Authorization': 'Bearer $token',
        'Content-Type': 'application/json',
      },
    );

    if (response.statusCode == 200) {
      final List<dynamic> data = jsonDecode(utf8.decode(response.bodyBytes));
      List<Contact> contacts = data.map((json) => Contact.fromJson(json)).toList();
      for (var contact in contacts) {
        if (contact.lastMessageTime != null) {
          DateTime serverTime = contact.lastMessageTime!;
          contact = contact.copyWith(lastMessageTime: serverTime.add(offset));
        }
      }
      return contacts;
    } else {
      throw Exception('Failed to load contacts');
    }
  }

  Future<Contact> fetchContactById(int userId) async {
    final token = await _apiService.getAccessToken();
    final response = await _client.get(
      Uri.parse('${AppConstants.baseUrl}/users/$userId'),
      headers: {
        'Authorization': 'Bearer $token',
        'Content-Type': 'application/json',
      },
    );

    if (response.statusCode == 200) {
      final data = jsonDecode(utf8.decode(response.bodyBytes));
      return Contact.fromJson(data);
    } else {
      throw Exception('Не удалось загрузить данные контакта');
    }
  }
}
