import 'package:account/src/features/personal_data/domain/entities/update_user_request_entity.dart';
import 'package:account/src/features/personal_data/domain/update_user_use_case.dart';
import 'package:account/src/features/personal_data/presentation/providers/update_user_use_case_provider.dart';
import 'package:account/src/features/personal_data/presentation/state/personal_data_view_state.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:legacy_shared/legacy_shared.dart';
// import 'package:sf_localizations/sf_localizations.dart';

final personalDataViewModelProvider =
NotifierProvider.autoDispose<PersonalDataViewModel, PersonalDataViewState>(
  PersonalDataViewModel.new,
);

class PersonalDataViewModel extends Notifier<PersonalDataViewState> {
  late final UpdateUserUseCase _updateUserUseCase;

  late final TextEditingController nameController;
  late final TextEditingController emailController;
  late final TextEditingController phoneController;
  late final TextEditingController passwordController;

  @override
  PersonalDataViewState build() {
    _updateUserUseCase = ref.read(updateUserUseCaseProvider);

    nameController = TextEditingController();
    nameController.addListener(_onNameChanged);

    emailController = TextEditingController();
    emailController.addListener(_onEmailChanged);

    phoneController = TextEditingController();
    phoneController.addListener(_onPhoneChanged);

    passwordController = TextEditingController();
    passwordController.addListener(_onPasswordChanged);

    ref.read(loggedUserProvider.future)
        .then(setUser);

    ref.onDispose(disposeControllers);

    return const PersonalDataViewState();
  }

  void setUser(UserEntity user) {
    state = state.copyWith(user: user);
  }

  void _onNameChanged() {
    final value = nameController.text;

    if (value == state.name) return;

    state = state.copyWith(
      name: value,
    );
  }

  void _onEmailChanged() {
    final value = emailController.text;

    if (value == state.email) return;

    state = state.copyWith(
      email: value,
    );
  }

  void _onPhoneChanged() {
    final value = phoneController.text;

    if (value == state.phoneNumber) return;

    state = state.copyWith(
      phoneNumber: value,
    );
  }

  void _onPasswordChanged() {
    final value = passwordController.text;

    if (value == state.password) return;

    state = state.copyWith(
      password: value,
    );
  }

  bool _validateForm() {
    if (state.name.trim().isEmpty &&
        state.email.trim().isEmpty &&
        state.phoneNumber.trim().isEmpty &&
        state.password.trim().isEmpty) {
      state = state.copyWith(errorMessage: 'errorMessageAllFieldsAreEmpty');
      return false;
    }
    return true;
  }

  UpdateUserRequestEntity _toRequest() {

    return UpdateUserRequestEntity(
      id: state.user!.id,
      //name: state.name.trim(),
      email: state.email.trim(),
      phone: /*state.dialCode.trim() + */state.phoneNumber.trim(),
    );
  }

  Future<bool> updateUser() async {
    if (state.isLoading) return false;
    if (!_validateForm()) return false;

    try {
      final request = _toRequest();

      _updateUserUseCase.updateUser(userId: state.user!.id, request: request);
      ref.invalidate(loggedUserProvider);

      return true;
    } catch (e) {
      if (!ref.mounted) return false;
      _finishWithError(message: e.toString());
      return false;
    }

  }

  void _finishWithError({required String message}) {
    state = state.copyWith(
      isLoading: false,
      errorMessage: message,
    );
  }

  void disposeControllers() {
    nameController.removeListener(_onNameChanged);
    nameController.dispose();

    emailController.removeListener(_onEmailChanged);
    emailController.dispose();

    phoneController.removeListener(_onPhoneChanged);
    phoneController.dispose();

    passwordController.removeListener(_onPasswordChanged);
    passwordController.dispose();

  }
}