import 'dart:io';

import 'package:cheminova/utils/constants.dart';
import 'package:cheminova/utils/show_snackbar.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

Future<BodyType?> commonApiService<BodyType>({
  required String url,
  required String method,
  Map<String, dynamic> body = const {},
  File? imageFile,
  bool isformData = true,
  Map<String, String>? additionalHeaders,
  required BodyType Function(Map<String, dynamic>) fromJson,
}) async {
  try {
    Dio dio = Dio();
    final Response response;

    print("body : $body");

    // Fetch the token from SharedPreferences
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? token = prefs.getString('token');

    Map<String, String> headers = {
      'Content-Type': isformData ? 'multipart/form-data' : 'application/json',
    };

    if (token != null) {
      headers['Authorization'] = 'Bearer $token';
    }

    if (additionalHeaders != null) {
      headers.addAll(additionalHeaders);
    }
    Options options = Options(headers: headers);

    FormData formData = FormData.fromMap(body);

    if (imageFile != null) {
      String fileName = imageFile.path.split('/').last;
      formData.files.add(MapEntry(
        "image",
        await MultipartFile.fromFile(imageFile.path, filename: fileName),
      ));
    }

    if (method == "POST") {
      response = await dio.post("$baseUrl$url",
          data: isformData ? formData : body, options: options);

    } else if (method == "PUT") {
      response = await dio.put("$baseUrl$url",
          data: isformData ? formData : body, options: options);
    } else if (method == "DELETE") {
      response = await dio.delete("$baseUrl$url", options: options);
    } else if (method == "PATCH") {
      response = await dio.patch("$baseUrl$url",
          data: isformData ? formData : body, options: options);
    } else {
      response = await dio.get("$baseUrl$url", options: options);
    }

    print("response of $url : $response");

    if (url == "/api/v1/user/login/" &&
        response.data['token'] != null) {
      prefs.setString('token', response.data['token']);
    }

    // if (url == "/api/territorymanager/my-profile") {
    //   return fromJson(response.data['myData']);
    // }

    return fromJson(response.data);
  } on DioException catch (e) {
    print("dio exception $url ${e.response?.data}}");

    print("dio exception details: ${e.message} ${e.response?.statusCode}");
    String errorMessage = "An error occurred";

    if (e.response?.data is Map<String, dynamic>) {
      errorMessage = e.response?.data['message'] ?? errorMessage;
    } else if (e.response?.data is String) {
      errorMessage = e.response?.data;
    }

    //showSnackbar(errorMessage);
  } catch (e) {
    print("exception $url $e");
  }
  return null;
}
