import 'dart:io';

import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:http_parser/http_parser.dart';
import 'package:injectable/injectable.dart';
import 'package:krow/core/application/clients/api/api_client.dart';
import 'package:krow/core/application/clients/api/api_exception.dart';
import 'package:krow/core/application/clients/api/gql.dart';
import 'package:krow/core/data/models/staff_role.dart';
import 'package:krow/features/profile/role_kit/data/models/mutate_kit_dto.dart';
import 'package:krow/features/profile/role_kit/data/staf_kit_gql.dart';

@injectable
class StaffRoleKitApiProvider {
  final ApiClient _apiClient;

  StaffRoleKitApiProvider(this._apiClient);

  Future<List<StaffRole>> fetchStaffRoles() async {
    var result = await _apiClient.query(schema: getStaffRolesQuery);

    if (result.hasException) {
      throw parseBackendError(result.exception);
    }

    return result.data!['staff_roles'].map<StaffRole>((e) {
      return StaffRole.fromJson(e);
    }).toList();
  }

  Future<void> putUniform(String skillId, List<MutateKitDto> kits) async {
    final Map<String, dynamic> variables = {
      'skillId': skillId,
      'uniforms': kits,
    };
    var result = await _apiClient.mutate(
        schema: confirmStaffUniformsMutation, body: variables);

    if (result.hasException) {
      throw parseBackendError(result.exception);
    }
  }

  Future<void> putEquipment(String skillId, List<MutateKitDto> kits) async {
    final Map<String, dynamic> variables = {
      'skillId': skillId,
      'equipments': kits,
    };
    var result = await _apiClient.mutate(
        schema: confirmStaffEquipmentsMutation, body: variables);
    if (result.hasException) {
      throw parseBackendError(result.exception);
    }
  }

  Future<Map<String, dynamic>> uploadImage(String imagePath) async {
    final ApiClient apiClient = ApiClient();

    var byteData = File(imagePath).readAsBytesSync();

    var multipartFile = MultipartFile.fromBytes(
      'photo',
      byteData,
      filename: '${DateTime.now().millisecondsSinceEpoch}.jpg',
      contentType: MediaType('image', 'jpg'),
    );

    final Map<String, dynamic> variables = {
      'file': multipartFile,
    };

    final result = await apiClient.mutate(
      schema: uploadImageMutation,
      body: variables,
    );

    if (result.hasException) {
      debugPrint(result.exception.toString());
    } else {
      return result.data!['upload_file'];
    }
    return <String, dynamic>{};
  }
}
