import 'package:get/get.dart';
import 'package:mypoint_flutter_app/core/utils/extensions/string_extension.dart';
import 'package:mypoint_flutter_app/core/network/restful_api_client_all_request.dart';
import 'package:mypoint_flutter_app/features/personal/personal_edit_item_model.dart';
import 'package:mypoint_flutter_app/features/personal/personal_gender.dart';
import '../../core/network/restful_api_viewmodel.dart';
import '../../app/config/constants.dart';
import '../../core/services/web/web_info_data.dart';
import '../../shared/preferences/data_preference.dart';
import '../../shared/router_gage.dart';
import '../../core/utils/validation_utils.dart';
import '../location_address/location_address_viewmodel.dart';

class PersonalEditViewModel extends RestfulApiViewModel {
  var editDataModel = Rxn<PersonalEditDataModel>();
  var province = Rxn<AddressBaseModel>();
  var district = Rxn<AddressBaseModel>();
  DateTime? birthday;
  PersonalGender? gender;
  RxBool isValidate = false.obs;
  void Function(String message)? onShowAlertError;
  void Function()? updateProfileResponseSuccess;

  @override
  void onInit() {
    super.onInit();
    final profile = DataPreference.instance.profile;
    if (profile == null) return;
    province.value = AddressBaseModel(
      code: profile.workerSite?.locationProvinceCode,
      name: profile.workerSite?.locationProvinceName,
    );
    district.value = AddressBaseModel(
      code: profile.workerSite?.locationDistrictCode,
      name: profile.workerSite?.locationDistrictName,
    );
    birthday = profile.workerSite?.birthday?.toDateFormat('yyyy-MM-dd');
    gender = PersonalGender.from(profile.workerSite?.sex ?? "U");
    // var webGender =  WebData.getGender().orEmpty;
    // if (webGender.isNotEmpty) {
    //   gender = PersonalGender.fromInt(webGender);
    // }
    // var name = WebData.getFullName() ?? profile.workerSite?.fullname ?? "";
    // var email = WebData.getEmail() ?? profile.workerSite?.email;
    // var address = WebData.getAddress() ?? profile.workerSite?.addressFull;
    // var identification = WebData.getIdentityNumber() ?? profile.workerSite?.identificationNumber;
    var name = profile.workerSite?.fullname ?? "";
    var email = profile.workerSite?.email;
    var address = profile.workerSite?.addressFull;
    var identification = profile.workerSite?.identificationNumber;

    editDataModel.value = PersonalEditDataModel(
      name: name,
      nickname: profile.workerSite?.nickname,
      phone: profile.workerSite?.phoneNumber,
      email: email,
      identificationNumber: identification,
      birthday: birthday,
      gender: gender,
      address: address,
      province: province.value,
      district: district.value,
      avatar: profile.workerSite?.avatar2,
    );
    isValidate.value = validate();
  }

  void updateItemEditData(PersonalEditItemModel item, String value) {
    if (editDataModel.value == null) return;
    switch (item.sectionType ?? SectionPersonalEditType.nickname) {
      case SectionPersonalEditType.name:
        editDataModel.value?.name = value;
        break;
      case SectionPersonalEditType.nickname:
        editDataModel.value?.nickname = value;
        break;
      case SectionPersonalEditType.phone:
        editDataModel.value?.phone = value;
        break;
      case SectionPersonalEditType.email:
        editDataModel.value?.email = value;
        break;
      case SectionPersonalEditType.identificationNumber:
        editDataModel.value?.identificationNumber = value;
        break;
      case SectionPersonalEditType.address:
        editDataModel.value?.address = value;
        break;
      default:
        break;
    }
  }

  Future<void> uploadAvatarAndSet(String imagePath) async {
    final feedbackId = DataPreference.instance.profile?.workerSite?.id ?? "";
    if (feedbackId.isEmpty) {
      editDataModel.value?.avatar = imagePath;
      editDataModel.refresh();
      return;
    }
    showLoading();
    try {
      final res = await client.uploadImage(imagePath, feedbackId);
      hideLoading();
      final imageId = res.data?.imageId;
      print("uploadAvatarAndSet imageId ${imageId}");
      if (res.isSuccess && imageId != null && imageId.isNotEmpty) {
        editDataModel.value?.avatar = imageId;
        editDataModel.refresh();
      } else {
        onShowAlertError?.call(res.errorMessage ?? Constants.commonError);
      }
    } catch (_) {
      hideLoading();
      onShowAlertError?.call(Constants.commonError);
    }
  }

  Future<void> updateProfile() async {
    showLoading();
    try {
      final body = editDataModel.value?.body ?? {};
      final response = await client.updateWorkerSiteProfile(body);
      hideLoading();
      if (response.status?.toLowerCase() == "success") {
        updateProfileResponseSuccess?.call();
        _getUserProfile();
      } else {
        onShowAlertError?.call(response.errorMessage ?? Constants.commonError);
      }
    } catch (error) {
      hideLoading();
      onShowAlertError?.call(Constants.commonError);
    }
  }

  void _getUserProfile() {
    client.getUserProfile().then((value) async {
      final userProfile = value.data;
      if (value.isSuccess && userProfile != null) {
        DataPreference.instance.saveUserProfile(userProfile);
      }
    });
  }

  Future<void> navigateToLocationScreen(PersonalEditItemModel item) async {
    if (item.sectionType == null) return;
    if (item.sectionType == SectionPersonalEditType.province) {
      final result = await Get.toNamed(
        locationAddressScreen,
        arguments: {"type": "province", "selectedCode": province.value?.code ?? ""},
      );
      if (result is AddressBaseModel && result.code != province.value?.code) {
        province.value = result;
        district.value = null;
        editDataModel.value?.district = null;
        editDataModel.value?.province = result;
        editDataModel.refresh();
      }
    } else if (item.sectionType == SectionPersonalEditType.district && (province.value?.code ?? "").isNotEmpty) {
      final result = await Get.toNamed(
        locationAddressScreen,
        arguments: {
          "type": "district",
          "selectedCode": district.value?.code ?? "",
          "provinceCode": province.value?.code ?? "",
        },
      );
      if (result is AddressBaseModel) {
        district.value = result;
        editDataModel.value?.district = result;
        editDataModel.refresh();
      }
    }
    isValidate.value = validate();
  }

  bool validate() {
    final model = editDataModel.value;
    if (model == null) return false;

    if ((model.name ?? '').isEmpty) {
      return false;
    }
    if (model.birthday == null) {
      return false;
                             }
    if (model.gender == null || model.gender == PersonalGender.unknown) {
      return false;
    }
    if ((model.email ?? '').isNotEmpty && !isValidEmail(model.email!)) {
      return false;
    }
    return true;
  }

  bool isValidEmail(String email) {
    return ValidationUtils.isValidEmail(email);
  }
}
