import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:functions/src/features/contacts/domain/entities/contact_entity.dart';
import 'package:functions/src/features/contacts/domain/get_contacts_use_case.dart';
import 'package:functions/src/features/contacts/presentation/providers/get_contacts_use_case_provider.dart';
import 'package:functions/src/features/contacts/presentation/state/contacts_view_state.dart';
// import 'package:legacy_shared/src/providers/logged_user_provider.dart';
// import 'package:legacy_shared/src/data/models/entities/user_entity.dart';
// import 'package:sf_localizations/sf_localizations.dart';

final contactsViewModelProvider =
NotifierProvider.autoDispose<ContactsViewModel, ContactsViewState>(
  ContactsViewModel.new,
);

class ContactsViewModel extends Notifier<ContactsViewState> {
  late final GetContactsUseCase _getContactsUseCase;

  late final TextEditingController nameController;
  late final TextEditingController phoneController;

  // late final UserEntity loggedUser;

  @override
  ContactsViewState build() {
    _getContactsUseCase = ref.read(getContactsUseCaseProvider);

    // loggedUser = ref.read(loggedUserProvider);

    nameController = TextEditingController();
    phoneController = TextEditingController();

    nameController.addListener(_onNameChanged);
    phoneController.addListener(_onPhoneChanged);

    _getContactsUseCase.getContacts(userId: '').then(setContacts);

    ref.onDispose(disposeControllers);

    return const ContactsViewState();
  }

  void setContacts(List<ContactEntity> contacts) {
    state = state.copyWith(
      contacts: contacts
    );
  }

  void toggleIsEditing() {
    state = state.copyWith(isEditing: !state.isEditing);
  }

  void _onNameChanged() {
    final text = nameController.text;
    if (text == state.name) return;

    state = state.copyWith(name: text, errorMessage: '');
  }

  void _onPhoneChanged() {
    final text = phoneController.text;
    if (text == state.phone) return;

    state = state.copyWith(phone: text, errorMessage: '');
  }

  void updateContact(ContactEntity contact) {

  }

  void disposeControllers() {
    nameController.removeListener(_onNameChanged);
    phoneController.removeListener(_onPhoneChanged);

    nameController.dispose();
    phoneController.dispose();
  }
}
