import 'dart:developer';

import 'package:dartz/dartz.dart';
import 'package:data_channel/data_channel.dart';
import 'package:flutter/widgets.dart';
import 'package:injectable/injectable.dart';

import '../../../common/api/api_client.dart';
import '../../../common/api/api_failure.dart';
import '../../../common/function/app_function.dart';
import '../../../common/url/api_path.dart';
import '../../../domain/table/table.dart';
import '../table_dtos.dart';

@injectable
class TableRemoteDataProvider {
  final ApiClient _apiClient;
  final _logName = 'TableRemoteDataProvider';

  TableRemoteDataProvider(this._apiClient);

  Future<DC<TableFailure, ListTableDto>> fetchTables({
    int page = 1,
    int limit = 50,
    String? status,
  }) async {
    try {
      Map<String, dynamic> queryParameters = {'page': page, 'limit': limit};

      if (status != null) {
        queryParameters['status'] = status;
      }

      final response = await _apiClient.get(
        ApiPath.tables,
        headers: getAuthorizationHeader(),
        params: queryParameters,
      );

      if (response.data['data'] == null) {
        return DC.error(const TableFailure.empty());
      }

      final tables = ListTableDto.fromJson(
        response.data['data'] as Map<String, dynamic>,
      );

      return DC.data(tables);
    } on ApiFailure catch (e, s) {
      log('fetchTablesError', name: _logName, error: e, stackTrace: s);
      return DC.error(TableFailure.serverError(e));
    }
  }

  Future<DC<TableFailure, TableDto>> storeTable({
    required String outletId,
    required String name,
    required int capacity,
  }) async {
    try {
      final response = await _apiClient.post(
        ApiPath.tables,
        data: {
          'outlet_id': outletId,
          'table_name': name,
          'capacity': capacity,
          'position_x': 200,
          'position_y': 200,
        },
        headers: getAuthorizationHeader(),
      );

      if (response.data['success'] == false) {
        return DC.error(const TableFailure.unexpectedError());
      }

      final table = TableDto.fromJson(
        response.data['data'] as Map<String, dynamic>,
      );
      return DC.data(table);
    } on ApiFailure catch (e, s) {
      log('storeTableError', name: _logName, error: e, stackTrace: s);
      return DC.error(TableFailure.serverError(e));
    }
  }

  Future<DC<TableFailure, TableDto>> updatePosition({
    required String id,
    required Offset position,
  }) async {
    try {
      final response = await _apiClient.put(
        '${ApiPath.tables}/$id',
        data: {
          'position_x': position.dx.round(),
          'position_y': position.dy.round(),
        },
        headers: getAuthorizationHeader(),
      );

      if (response.data['success'] == false) {
        return DC.error(const TableFailure.unexpectedError());
      }

      final table = TableDto.fromJson(
        response.data['data'] as Map<String, dynamic>,
      );
      return DC.data(table);
    } on ApiFailure catch (e, s) {
      log('updatePositionTableError', name: _logName, error: e, stackTrace: s);
      return DC.error(TableFailure.serverError(e));
    }
  }

  Future<DC<TableFailure, Unit>> transferTable({
    required String fromTableId,
    required String toTableId,
  }) async {
    try {
      final response = await _apiClient.put(
        '${ApiPath.tables}/transfer',
        data: {'from_table': fromTableId, 'to_table': toTableId},
        headers: getAuthorizationHeader(),
      );

      if (response.data['success'] == false) {
        return DC.error(const TableFailure.unexpectedError());
      }

      return DC.data(unit);
    } on ApiFailure catch (e, s) {
      log('transferTableError', name: _logName, error: e, stackTrace: s);
      return DC.error(TableFailure.serverError(e));
    }
  }
}
