<%
  content_name = f.object.class.content_name

  field_id = "#{content_name}_#{field.name}"
  value = nil
  if f.object.respond_to?(field.name.to_sym)
    value = f.object.send(field.name.to_sym)
  else
    value = field.attribute_values.find_by(
      user: f.object.user,
      entity_type: f.object.class.name,
      entity_id: f.object.id
    )
  end
%>

<div class="input-field content-field">
  <% unless defined?(show_label) && !show_label %>
    <%= f.label field do %>
      <%= field.label.present? ? field.label : ' ' %>
      <% if defined?(autocomplete) && autocomplete %>
        <i class="material-icons grey-text lighten-2 tooltipped" style="font-size: 100%" data-tooltip="This field may suggest some ideas for you when you start typing." data-position="right">
          offline_bolt
        </i>
      <% end %>
    <% end %>
  <% end %>
  <%
    placeholder = I18n.translate "attributes.#{content_name}.#{field.name}",
      scope: :serendipitous_questions,
      name: f.object.send('name') || "this #{content_name}",
      default: 'Write as little or as much as you want!'
  %>

  <%= hidden_field_tag "#{content_name}[custom_attribute_values][][name]", field.name %>
  <%=
    text_area_tag "#{content_name}[custom_attribute_values][][value]",
                  value && value.value,
                  class: "js-can-mention-pages materialize-textarea #{defined?(autocomplete) && autocomplete ? ('autocomplete ' + 'js-autocomplete-' + field.id.to_s) : ''}",
                  placeholder: placeholder
  %>
</div>

<% if defined?(autocomplete) && autocomplete %>
  <%= content_for :javascript do %>
    $(function() {
      // This setTimeout is an unfortunate hack to ensure this runs after initializing materialize
      setTimeout(function() {
        console.log("Initializing autocomplete for #<%= "#{content_name}_#{field.label}" %>");

        $('.js-autocomplete-<%= field.id.to_s %>').autocomplete({
          limit: 5,
          data: {
            <% autocomplete.each do |autocomplete_option| %>
              "<%= autocomplete_option %>": null,
            <% end %>
          }
        });
      }, 1000);
    });
  <% end %>
<% end %>
