ActiveAdmin.register AdminUser do
  menu priority: 8, label: "🔑 Admin Users"
  permit_params :email, :password, :password_confirmation, :member_id

  index do
    selectable_column
    id_column
    column :email
    column(:member) { |u| u.member ? link_to(u.member.nick, admin_member_path(u.member)) : "–" }
    column :created_at
    actions
  end

  filter :email
  filter :member_id, as: :select, collection: -> { Member.order(:nick).map { |m| [ m.nick, m.id ] } }
  filter :created_at

  form do |f|
    f.inputs do
      f.input :email
      f.input :password, hint: "Leave blank to keep current password"
      f.input :password_confirmation
      f.input :member_id, as: :select,
              collection: Member.order(:nick).map { |m| [ m.nick, m.id ] },
              include_blank: "— none —"
    end
    f.actions
  end

  show do
    attributes_table do
      row :id
      row :email
      row(:member) { |u| u.member ? link_to(u.member.nick, admin_member_path(u.member)) : "–" }
      row :created_at
      row :updated_at
    end
  end

  controller do
    def scoped_collection
      super.includes(:member)
    end

    def update
      if params[:admin_user][:password].blank?
        params[:admin_user].delete(:password)
        params[:admin_user].delete(:password_confirmation)
      end
      super
    end
  end
end
