import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:injectable/injectable.dart';
import 'package:location/base/base_controller.dart';
import 'package:location/data/bean/user_info.dart';
import 'package:location/data/repositories/friends_repository.dart';
import 'package:location/handler/error_handler.dart';
import 'package:location/resource/string.gen.dart';

import '../../../dialog/common_alert_dialog_impl.dart';
import '../../../dialog/friend_update_remark_dialog.dart';
import '../../../utils/common_util.dart';
import '../../../utils/toast_util.dart';

@injectable
class FriendSettingController extends BaseController {
  final Rxn<UserInfo> _userInfo = Rxn<UserInfo>();

  UserInfo? get userInfo => _userInfo.value;

  final FriendsRepository friendsRepository;

  FriendSettingController(this.friendsRepository);

  @override
  void onInit() {
    final param = Get.arguments;
    if (param is UserInfo) {
      _userInfo.value = param;
    }
  }

  void back() {
    Get.back();
  }

  void editRemarkClick() {
    FriendUpdateRemarkDialog.show(
        remark: userInfo?.remark,
        callback: (remark) {
          if (remark == userInfo?.remark) {
            ToastUtil.show(StringName.remarkNoChange);
            return;
          }
          _updateRemark(remark);
        });
  }

  void _updateRemark(String remark) {
    friendsRepository.updateFriendRemark(userInfo?.id ?? '', remark).then((_) {
      ToastUtil.show(StringName.remarkUpdateSuccess);
      FriendUpdateRemarkDialog.dismiss();
      userInfo?.remark = remark;
      _userInfo.refresh();
    }).catchError((error) {
      ErrorHandler.toastError(error);
    });
  }

  void copyPhoneClick() {
    copyToClipboard(userInfo?.phoneNumber ?? '');
    ToastUtil.show(StringName.copyPhoneNumSuccess);
  }

  Future<bool> blockHimFuture(bool isChecked) async {
    if (userInfo == null) {
      return false;
    }
    bool isBlocked = userInfo?.blockedHim ?? false;
    try {
      await Future.delayed(Duration(seconds: 3));
      await friendsRepository.updateFriendBlocked(
          friendId: userInfo?.id ?? '', blocked: !isBlocked);
      if (!isBlocked) {
        ToastUtil.show(StringName.blockedFriend);
      } else {
        ToastUtil.show(StringName.blockFriendOff);
      }
      userInfo?.blockedHim = !isBlocked;
      return !isBlocked;
    } catch (e) {
      ErrorHandler.toastError(e);
      return isBlocked;
    }
  }

  void deleteFriendClick() {
    deleteFriendDialog(confirmOnTap: () {
      _deleteFriendFuture();
    });
  }

  void _deleteFriendFuture() {
    final friendId = userInfo?.id ?? '';
    friendsRepository.deleteFriend(friendId).then((data) {
      ToastUtil.show(StringName.deleteSuccess);
      Get.back();
    }).catchError((error) {
      ErrorHandler.toastError(error);
    });
  }
}
