<% close_on_submit = local_assigns.fetch(:close_on_submit, true) %>
<% is_order_set = template.submitters.any? { |s| s['order'] } %>
<%= form_for template, url: template_recipients_path(template), method: :post, html: { autocomplete: 'off', class: 'mt-1', id: :submitters_form }, data: { close_on_submit: } do |f| %>
  <% unless close_on_submit %>
    <toggle-on-submit data-element-id="form_saved_alert"></toggle-on-submit>
  <% end %>
  <div class="space-y-3 divide-y">
    <% template.submitters.each_with_index do |submitter, index| %>
      <div class="<%= 'pt-3' if index.positive? %>">
        <%= f.fields_for :submitters, item = Struct.new(:name, :uuid, :is_requester, :email, :invite_by_uuid, :invite_via_field_uuid, :optional_invite_by_uuid, :linked_to_uuid, :order, :option).new(*submitter.values_at('name', 'uuid', 'is_requester', 'email', 'invite_by_uuid', 'invite_via_field_uuid', 'optional_invite_by_uuid', 'linked_to_uuid', 'order')), index: do |ff| %>
          <% item.option = item.is_requester.present? ? 'is_requester' : (item.email.present? ? 'email' : (item.linked_to_uuid.present? ? "linked_to_#{item.linked_to_uuid}" : (item.invite_by_uuid.present? ? "invite_by_#{item.invite_by_uuid}" : (item.optional_invite_by_uuid.present? ? "optional_invite_by_#{item.optional_invite_by_uuid}" : (item.invite_via_field_uuid.present? ? 'invite_via_field' : ''))))) %>
          <%= ff.hidden_field :uuid %>
          <div class="form-control">
            <div class="flex justify-between">
              <%= ff.text_field :name, class: 'w-full outline-none border-transparent focus:border-transparent focus:ring-0 bg-base-100 px-1 peer mb-2', autocomplete: 'off', placeholder: "#{index + 1}#{(index + 1).ordinal} Party", required: true %>
              <% if template.submitters.size > 2 %>
                <div id="order_<%= submitter['uuid'] %>" class="mr-0.5">
                  <% if is_order_set %>
                    <%= ff.select :order, options_for_select(template.submitters.map.with_index { |_, i| [(i + 1).ordinalize, i] }, submitter['order'].presence || index), {}, class: 'select select-xs text-sm input-bordered bg-white pl-3.5' %>
                  <% elsif index == 0 %>
                    <mount-on-click data-template-id="order_fields" class="link whitespace-nowrap text-sm mt-1 mr-1 block">
                      <%= t('edit_order') %>
                    </mount-on-click>
                  <% end %>
                </div>
              <% end %>
            </div>
            <% if template.submitters.size == 2 %>
              <%= tag.input name: ff.field_name(:email), value: ff.object.email, type: :email, multiple: true, autocomplete: 'off', placeholder: t('default_email'), id: email_field_uuid = SecureRandom.uuid, disabled: is_email_disabled = ff.object.is_requester || ff.object.invite_by_uuid.present? || ff.object.optional_invite_by_uuid.present? || ff.object.invite_via_field_uuid.present?, class: "base-input w-full #{'hidden' if ff.object.invite_by_uuid.present? || ff.object.optional_invite_by_uuid.present? || ff.object.invite_via_field_uuid.present?}" %>
              <% if index == 1 %>
                <% invite_fields = template.fields.select { |field| field['name'].present? && field['submitter_uuid'] != submitter['uuid'] } %>
                <disable-hidden id="<%= invite_by_selector_id = SecureRandom.uuid %>" class="<%= 'hidden' if ff.object.invite_by_uuid.blank? && ff.object.optional_invite_by_uuid.blank? && ff.object.invite_via_field_uuid.blank? %>">
                  <toggle-attribute data-target-id="<%= invite_via_field_selector_id = SecureRandom.uuid %>" data-class-name="hidden" data-value="invite_via_field">
                    <%= ff.select :option, [*(template.submitters - [submitter]).flat_map { |e| [[t('invite_by_name', name: e['name']), "invite_by_#{e['uuid']}"], [t('invite_by_name', name: e['name']) + " (#{t(:optional).capitalize})", "optional_invite_by_#{e['uuid']}"]] }, (invite_fields.present? ? [t('invite_via_form_field'), 'invite_via_field'] : nil)].compact, {}, class: 'base-select' %>
                  </toggle-attribute>
                  <% if invite_fields.present? %>
                    <disable-hidden id="<%= invite_via_field_selector_id %>" class="mt-2 <%= 'hidden' if ff.object.invite_via_field_uuid.blank? %>">
                      <%= select_tag ff.field_name(:invite_via_field_uuid), options_for_select(invite_fields.map { |field| [field['name'], field['uuid']] }, ff.object.invite_via_field_uuid), prompt: t(:select_field), class: 'base-select mt-3' %>
                    </disable-hidden>
                  <% end %>
                </disable-hidden>
              <% end %>
            <% else %>
              <% invite_fields = template.fields.select { |field| field['name'].present? && field['submitter_uuid'] != submitter['uuid'] } %>
              <toggle-attribute data-target-id="<%= email_field_uuid = SecureRandom.uuid %>" data-class-name="hidden" data-value="email">
                <toggle-attribute data-target-id="<%= invite_field_wrapper_uuid = SecureRandom.uuid %>" data-class-name="hidden" data-value="invite_via_field">
                  <%= ff.select :option, [[t('not_specified'), 'not_set'], (local_assigns[:with_submission_requester] == false ? nil : [t('submission_requester'), 'is_requester']), [t('specified_email'), 'email'], *(template.submitters - [submitter]).flat_map { |e| [[t('invite_by_name', name: e['name']), "invite_by_#{e['uuid']}"], [t('invite_by_name', name: e['name']) + " (#{t(:optional).capitalize})", "optional_invite_by_#{e['uuid']}"]] }, *(template.submitters - [submitter]).map { |e| [t('same_as_name', name: e['name']), "linked_to_#{e['uuid']}"] }, (invite_fields.present? ? [t('invite_via_form_field'), 'invite_via_field'] : nil)].compact, {}, class: 'base-select mb-3' %>
                </toggle-attribute>
              </toggle-attribute>
              <%= tag.input name: ff.field_name(:email), type: :email, value: ff.object.email, multiple: true, class: "base-input #{'hidden' if item.option != 'email'}", autocomplete: 'off', placeholder: t('default_email'), id: email_field_uuid %>
              <% if invite_fields.present? %>
                <disable-hidden id="<%= invite_field_wrapper_uuid %>" class="<%= 'hidden' if item.option != 'invite_via_field' %>">
                  <%= select_tag ff.field_name(:invite_via_field_uuid), options_for_select(invite_fields.map { |field| [field['name'], field['uuid']] }, item.invite_via_field_uuid), prompt: t(:select_field), class: 'base-select', required: true %>
                </disable-hidden>
              <% end %>
            <% end %>
          </div>
          <% if template.submitters.size == 2 %>
            <checkbox-group class="mt-3 flex items-center space-x-4">
              <% if index == 0 && local_assigns[:with_submission_requester] != false %>
                <label class="flex items-center space-x-2 cursor-pointer">
                  <toggle-attribute data-target-id="<%= email_field_uuid %>" class="flex" data-attribute="disabled">
                    <%= ff.check_box :is_requester, class: 'base-checkbox' %>
                  </toggle-attribute>
                  <span class="select-none">
                    <%= t('submission_requester') %>
                  </span>
                </label>
              <% elsif index == 1 %>
                <% if local_assigns[:with_submission_requester] != false %>
                  <toggle-classes data-target-id="<%= invite_by_selector_id %>" class="flex" data-classes="hidden" data-action="add">
                    <toggle-classes data-target-id="<%= email_field_uuid %>" class="flex" data-classes="hidden" data-action="remove">
                      <label class="flex items-center space-x-2 cursor-pointer">
                        <toggle-attribute data-target-id="<%= email_field_uuid %>" class="flex" data-attribute="disabled">
                          <%= ff.check_box :is_requester, class: 'base-checkbox' %>
                        </toggle-attribute>
                        <span class="select-none">
                          <%= t('submission_requester') %>
                        </span>
                      </label>
                    </toggle-classes>
                  </toggle-classes>
                <% end %>
                <label class="flex items-center space-x-2 cursor-pointer">
                  <toggle-attribute data-target-id="<%= email_field_uuid %>" class="flex" data-class-name="hidden" data-value="false">
                    <toggle-attribute data-target-id="<%= invite_by_selector_id %>" class="flex" data-class-name="hidden">
                      <toggle-attribute data-target-id="<%= email_field_uuid %>" class="flex" data-attribute="disabled">
                        <%= ff.check_box :invite_checbox, { class: 'base-checkbox', checked: ff.object.invite_by_uuid.present? || ff.object.optional_invite_by_uuid.present? || ff.object.invite_via_field_uuid.present? }, true, '' %>
                      </toggle-attribute>
                    </toggle-attribute>
                  </toggle-attribute>
                  <span class="select-none">
                    <%= t('invite_by_name', name: template.submitters.first['name']) %>
                  </span>
                </label>
              <% end %>
            </checkbox-group>
          <% end %>
        <% end %>
      </div>
    <% end %>
  </div>
<% end %>
<% if local_assigns[:with_toggles] != false %>
  <% unless current_account.account_configs.exists?(key: AccountConfig::ENFORCE_SIGNING_ORDER_KEY, value: true) %>
    <%= form_for template, url: template_preferences_path(template), method: :post, html: { autocomplete: 'off', class: 'mt-2' }, data: { close_on_submit: false } do |f| %>
      <div class="flex items-center pt-4 mt-4 justify-between border-t w-full">
        <span>
          <%= t('enforce_recipients_order') %>
        </span>
        <%= f.fields_for :preferences, Struct.new(:submitters_order).new(template.preferences['submitters_order']) do |ff| %>
          <submit-form data-on="change" class="flex">
            <%= ff.check_box :submitters_order, { class: 'toggle' }, 'preserved', '' %>
          </submit-form>
        <% end %>
      </div>
    <% end %>
  <% end %>
  <% if can?(:manage, :personalization_advanced) %>
    <%= form_for template, url: template_preferences_path(template), method: :post, html: { autocomplete: 'off', class: 'mt-2' }, data: { close_on_submit: false } do |f| %>
      <div class="flex items-center mt-4 justify-between w-full">
        <span>
          <%= t('ensure_unique_recipients') %>
        </span>
        <%= f.fields_for :preferences, Struct.new(:validate_unique_submitters).new(template.preferences['validate_unique_submitters']) do |ff| %>
          <submit-form data-on="change" class="flex">
            <%= ff.check_box :validate_unique_submitters, { class: 'toggle' }, 'true', '' %>
          </submit-form>
        <% end %>
      </div>
    <% end %>
  <% end %>
<% end %>
<div class="form-control mt-5">
  <%= button_tag button_title(title: t('save'), disabled_with: t('updating')), class: 'base-button', form: :submitters_form %>
  <% unless close_on_submit %>
    <div class="flex justify-center">
      <span id="form_saved_alert" class="text-sm invisible font-normal mt-0.5"><%= t('changes_have_been_saved') %></span>
    </div>
  <% end %>
</div>
<% if template.submitters.size > 2 && !is_order_set %>
  <template id="order_fields">
    <% template.submitters.each_with_index do |submitter, index| %>
      <turbo-stream action="replace" target="order_<%= submitter['uuid'] %>">
        <template>
          <div id="order_<%= submitter['uuid'] %>">
            <%= select_tag "template[submitters][#{index}][order]", options_for_select(template.submitters.map.with_index { |_, i| [(i + 1).ordinalize, i] }, submitter['order'].presence || index), class: 'select select-xs text-sm input-bordered bg-white pl-3.5' %>
          </div>
        </template>
      </turbo-stream>
    <% end %>
  </template>
<% end %>
