// ignore_for_file: use_build_context_synchronously

import 'package:flutter/material.dart';
import 'package:sfm_app/bloc/devices_manager_bloc.dart';
import 'package:sfm_app/product/shared/shared_snack_bar.dart';
import '../../product/utils/response_status_utils.dart';
import '../../product/constant/enums/role_enums.dart';
import '../../product/services/api_services.dart';
import '../../product/utils/qr_utils.dart';
import '../../product/constant/icon/icon_constants.dart';
import '../../product/extension/context_extension.dart';
import '../../product/services/language_services.dart';

addNewDevice(BuildContext context, String role, DevicesManagerBloc deviceManagerBloc) async {
  TextEditingController extIDController = TextEditingController(text: "");
  TextEditingController deviceNameController = TextEditingController(text: "");
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(
      dismissDirection: DismissDirection.none,
      duration: context.dynamicMinutesDuration(1),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '${appLocalization(context).add_device_title}: ',
                style: context.responsiveBodyLargeWithBold,
              ),
              Container(
                alignment: Alignment.centerRight,
                child: IconButton(
                    onPressed: () async {
                      ScaffoldMessenger.of(context).hideCurrentSnackBar();
                    },
                    icon: IconConstants.instance.getMaterialIcon(Icons.close)),
              )
            ],
          ),
          TextField(
            textInputAction: TextInputAction.next,
            controller: extIDController,
            decoration: InputDecoration(
                hintText: appLocalization(context).input_extID_device_hintText,
                suffixIcon: IconButton(
                    onPressed: () async {
                      String result =
                          await QRScanUtils.instance.scanQR(context);
                      extIDController.text = result;
                    },
                    icon: IconConstants.instance
                        .getMaterialIcon(Icons.qr_code_scanner_outlined))),
          ),
          role == RoleEnums.ADMIN.name
              ? TextField(
                  textInputAction: TextInputAction.done,
                  controller: deviceNameController,
                  decoration: InputDecoration(
                      hintText:
                          appLocalization(context).input_name_device_hintText),
                )
              : const SizedBox.shrink(),
          SizedBox(
            height: context.lowValue,
          ),
          Center(
            child: FilledButton.tonal(
              onPressed: () async {
                String extID = extIDController.text;
                String deviceName = deviceNameController.text;
                if (extID == "") {
                  showNoIconTopSnackBar(
                      context,
                      appLocalization(context).notification_enter_all_inf,
                      Colors.orange,
                      Colors.white);
                  ScaffoldMessenger.of(context).hideCurrentSnackBar();
                } else {
                  addDevices(context, role, extID, deviceName, deviceManagerBloc);
                  ScaffoldMessenger.of(context).hideCurrentSnackBar();
                }
              },
              child: Text(appLocalization(context).add_button_content),
            ),
          )
        ],
      ),
    ),
  );
}

void addDevices(
    BuildContext context, String role, String extID, String deviceName, DevicesManagerBloc deviceManagerBloc) async {
  APIServices apiServices = APIServices();
  Map<String, dynamic> body = {};
  if (role == RoleEnums.ADMIN.name) {
    try {
      body = {"ext_id": extID, "name": deviceName};
      int statusCode = await apiServices.createDeviceByAdmin(body);
      showSnackBarResponseByStatusCode(
          context,
          statusCode,
          appLocalization(context).notification_create_device_success,
          appLocalization(context).notification_create_device_failed);
      deviceManagerBloc.getDeviceByState(context,-2);
    } catch (e) {
      if (!context.mounted) return;
      showErrorTopSnackBarCustom(
          context, e.toString());
    }

  } else {
    try {
      body = {"ext_id": extID};
      int statusCode = await apiServices.registerDevice(body);
      showSnackBarResponseByStatusCode(
          context,
          statusCode,
          appLocalization(context).notification_add_device_success,
          appLocalization(context).notification_device_not_exist);
      deviceManagerBloc.getDeviceByState(context,-2);
    } catch (e) {
      if (!context.mounted) return;
      showErrorTopSnackBarCustom(
          context, e.toString());
    }
  }

}
