// ignore_for_file: use_build_context_synchronously

import 'package:flutter/material.dart';
import '../../bloc/devices_manager_bloc.dart';
import '../../product/constant/enums/role_enums.dart';
import '../../product/services/api_services.dart';
import '../../product/services/language_services.dart';
import '../../product/shared/shared_snack_bar.dart';
import '../../product/utils/response_status_utils.dart';

handleDeleteDevice(BuildContext context, DevicesManagerBloc devicesManagerBloc,
    extID, String role) {
  showDialog(
    context: context,
    builder: (dialogContext) {
      return AlertDialog(
        title: Text(appLocalization(dialogContext).delete_device_dialog_title),
        content:
            Text(appLocalization(dialogContext).delete_device_dialog_content),
        actions: <Widget>[
          TextButton(
            child: Text(appLocalization(dialogContext).cancel_button_content),
            onPressed: () {
              Navigator.of(dialogContext).pop();
            },
          ),
          TextButton(
            child: Text(
              appLocalization(dialogContext).delete_button_content,
              style: const TextStyle(color: Colors.red),
            ),
            onPressed: () async {
              await deleteOrUnregisterDevice(
                  context, devicesManagerBloc, extID, role);
              Navigator.of(dialogContext).pop();
            },
          ),
        ],
      );
    },
  );
}

deleteOrUnregisterDevice(BuildContext context, DevicesManagerBloc devicesBloc,
    String extID, String role) async {
  APIServices apiServices = APIServices();
  if (role == RoleEnums.USER.name) {
    Map<String, dynamic> body = {
      "ext_id": extID,
    };
    int statusCode = await apiServices.unregisterDevice(body);
    showSnackBarResponseByStatusCode(
        context,
        statusCode,
        appLocalization(context).notification_delete_device_success,
        appLocalization(context).notification_delete_device_failed);
    devicesBloc.getDeviceByState(context,-2);
  } else {
    try {
      int statusCode = await apiServices.deleteDeviceByAdmin(extID);
      showSnackBarResponseByStatusCode(
          context,
          statusCode,
          appLocalization(context).notification_delete_device_success,
          appLocalization(context).notification_delete_device_failed);
      devicesBloc.getDeviceByState(context,-2);
    } catch (e) {
      if (!context.mounted) return;
      showErrorTopSnackBarCustom(
          context, e.toString());
    }

  }
}
