import 'dart:convert';

import 'package:dio/dio.dart';
// import 'package:flutter/material.dart';
import 'package:functions/src/core/data/datasources/functions_remote_datasource.dart';
import 'package:functions/src/core/data/models/entities/locate_device_request_entity.dart';
import 'package:functions/src/core/data/models/entities/set_pedometer_request_entity.dart';
import 'package:functions/src/core/data/models/get_device_steps_response_model.dart';
import 'package:functions/src/core/data/models/send_command_request_model.dart';
import 'package:functions/src/features/activity_meter/domain/entities/activity_entity.dart';
import 'package:functions/src/features/contacts/domain/entities/contact_entity.dart';
import 'package:functions/src/features/remote_connection/domain/entities/picture_entity.dart';
import 'package:sf_infrastructure/sf_infrastructure.dart';

class FunctionsRemoteDatasourceImpl implements FunctionsRemoteDatasource {
  FunctionsRemoteDatasourceImpl(this._repository);

  final QuestiaRepository _repository;

  @override
  Future<List<ContactEntity>> getContacts({required String userId}) async {
    /*try {
      final response = await _repository.get<Map<String, dynamic>>(
        '/users/$userId/contacts',
      );

      final data = response.data;
      if (data == null || data.isEmpty) {
        throw Exception('Empty response from /users/:userId/contacts');
      }

      final model = GetContactsResponseModel.fromJson(data);
      return model.toEntity();
    } on DioException catch (error) {
      throw _mapDioError(error, defaultMessage: 'Error to get contacts');
    }*/
    return [
      ContactEntity(
        id: '1111',
        name: 'Ana',
        phone: '111111111',
        createdAt: 1,
        delegationId: null,
        groupId: null,
        userId: null,
        updatedAt: null,
      ),
      ContactEntity(
        id: '1112',
        name: 'Carlos',
        phone: '222222222',
        createdAt: 2,
        delegationId: null,
        groupId: null,
        userId: null,
        updatedAt: null,
      ),
    ];
  }

  @override
  Future<List<PictureEntity>> getPictures({required String userId}) async {
    /*try {
      final response = await _repository.get<Map<String, dynamic>>(
        '',
      );

      final data = response.data;
      if (data == null || data.isEmpty) {
        throw Exception('Empty response from /users/:userId/contacts');
      }

      final model = GetContactsResponseModel.fromJson(data);
      return model.toEntity();
    } on DioException catch (error) {
      throw _mapDioError(error, defaultMessage: 'Error to get contacts');
    }*/
    return [];
  }

  @override
  Future<PictureEntity> takePicture({required String userId}) async {
    /*try {
      final response = await _repository.get<Map<String, dynamic>>(
        '',
      );

      final data = response.data;
      if (data == null || data.isEmpty) {
        throw Exception('Empty response from /users/:userId/contacts');
      }

      final model = GetContactsResponseModel.fromJson(data);
      return model.toEntity();
    } on DioException catch (error) {
      throw _mapDioError(error, defaultMessage: 'Error to get contacts');
    }*/
    return PictureEntity(id: '1', userId: '1111', createdAt: 1111);
  }

  @override
  Future<void> locateDevice({required LocateDeviceRequestEntity request}) async {
    try {
      final body = request.toModel().toJson();
      await _repository.post<void>(
        '/commands',
        body: body,
      );
    } on DioException catch (error) {
      throw _mapDioError(
        error,
        defaultMessage: error.response?.data ?? 'Error to locate device',
      );
    }
  }

  @override
  Future<void> setPedometer({required SetPedometerRequestEntity request}) async {
    try {
      /*final body = request.toModel().toJson();
      await _repository.post<void>(
        '/commands',
        body: body,
      );*/
    } on DioException catch (error) {
      throw _mapDioError(
        error,
        defaultMessage: error.response?.data ?? 'Error to set pedometer',
      );
    }
  }

  @override
  Future<List<ActivityEntity>> getDeviceSteps({required String deviceId}) async {
    try {
      /*final response = await _repository.get<Map<String, dynamic>>(
        '/devices/identificator/$deviceId/steps',
      );

      final data = response.data;
      if (data == null || data.isEmpty) {
        throw Exception('Empty response from /devices/identificator/:deviceId/steps');
      }

      final model = GetDeviceStepsResponseModel.fromJson(data);*/
      final model = GetDeviceStepsResponseModel(items: [
        GetDeviceStepsItemResponseModel(
            id: '1',
            deviceIdentificator: '1111',
            steps: 200,
            totalSteps: 250,
            occurredAt: 1771933790000,
            createdAt: 0
        ),
        GetDeviceStepsItemResponseModel(
            id: '2',
            deviceIdentificator: '1111',
            steps: 500,
            totalSteps: 550,
            occurredAt: 1772020190000,
            createdAt: 0
        ),
        GetDeviceStepsItemResponseModel(
            id: '3',
            deviceIdentificator: '1111',
            steps: 200,
            totalSteps: 250,
            occurredAt: 1772106590000,
            createdAt: 0
        ),
        GetDeviceStepsItemResponseModel(
            id: '4',
            deviceIdentificator: '1111',
            steps: 1000,
            totalSteps: 1050,
            occurredAt: 1772192990000,
            createdAt: 0
        ),
        GetDeviceStepsItemResponseModel(
            id: '5',
            deviceIdentificator: '1111',
            steps: 200,
            totalSteps: 250,
            occurredAt: 1772279390000,
            createdAt: 0
        ),
        GetDeviceStepsItemResponseModel(
            id: '6',
            deviceIdentificator: '1111',
            steps: 100,
            totalSteps: 150,
            occurredAt: 1772365790000,
            createdAt: 0
        ),
        GetDeviceStepsItemResponseModel(
            id: '7',
            deviceIdentificator: '1111',
            steps: 300,
            totalSteps: 350,
            occurredAt: 1772455790000,
            createdAt: 0
        ),
      ]);
      return model.toEntity();
    } on DioException catch (error) {
      throw _mapDioError(error, defaultMessage: 'Error to get steps');
    }
  }
}

Exception _mapDioError(DioException error, {required String defaultMessage}) {
  final apiMsg = _extractApiMessage(error.response?.data);
  final msg = apiMsg ?? error.message ?? defaultMessage;
  return Exception(msg);
}

String? _extractApiMessage(Object? data) {
  if (data == null) return null;

  if (data is Map) {
    final errorObj = data['error'];
    if (errorObj is Map && errorObj['message'] is String) {
      return (errorObj['message'] as String).trim();
    }
    if (data['message'] is String) {
      return (data['message'] as String).trim();
    }
    return null;
  }

  if (data is String) {
    final raw = data.trim();
    if (raw.isEmpty) return null;

    try {
      final decoded = jsonDecode(raw);
      return _extractApiMessage(decoded);
    } catch (_) {
      return raw;
    }
  }

  return null;
}
