import 'package:flutter/material.dart';

import 'package:pweb/controllers/auth/account_name.dart';
import 'package:pweb/models/settings/profile_action_section.dart';


class ProfileActionsController extends ChangeNotifier {
  AccountNameController? _accountNameController;
  ProfileActionSection? _expandedSection;

  ProfileActionSection? get expandedSection => _expandedSection;
  bool get isEditingName => _accountNameController?.isEditing ?? false;

  bool isExpanded(ProfileActionSection section) => _expandedSection == section;

  void updateAccountNameController(AccountNameController controller) {
    if (identical(_accountNameController, controller)) {
      return;
    }
    _accountNameController?.removeListener(_handleAccountNameChanged);
    _accountNameController = controller;
    _accountNameController?.addListener(_handleAccountNameChanged);
  }

  void toggle(ProfileActionSection section) {
    final isOpeningSection = !isExpanded(section);
    if (isOpeningSection) {
      if (_accountNameController?.isBusy ?? false) {
        return;
      }
      _accountNameController?.cancelEditing();
    }
    _expandedSection = isExpanded(section) ? null : section;
    notifyListeners();
  }

  void toggleNameEditing() {
    final accountNameController = _accountNameController;
    if (accountNameController == null || accountNameController.isBusy) {
      return;
    }

    if (accountNameController.isEditing) {
      accountNameController.cancelEditing();
      return;
    }

    _expandedSection = null;
    accountNameController.startEditing();
    notifyListeners();
  }

  void _handleAccountNameChanged() {
    notifyListeners();
  }

  @override
  void dispose() {
    _accountNameController?.removeListener(_handleAccountNameChanged);
    super.dispose();
  }
}
