import 'package:get/get.dart';
import 'package:mypoint_flutter_app/extensions/string_extension.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import 'package:mypoint_flutter_app/screen/personal/personal_edit_item_model.dart';
import 'package:mypoint_flutter_app/screen/personal/personal_gender.dart';
import '../../networking/restful_api_viewmodel.dart';
import '../../configs/constants.dart';
import '../../preference/data_preference.dart';
import '../../shared/router_gage.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 name = profile?.workerSite?.fullname ?? "";

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

  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> 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);
      }
    });
  }

  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 == 'notAllowed') {
      return false;
    }
    if ((model.email ?? '').isNotEmpty && !isValidEmail(model.email!)) {
      return false;
    }
    return true;
  }

  bool isValidEmail(String email) {
    final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
    return emailRegex.hasMatch(email);
  }
}
