<% if action_name == "show" %>
  <% feedback_message_emails = @email_messages %>
<% else %>
  <% feedback_message_emails = @email_messages.select { |email| email.feedback_message_id == feedback_message.id } %>
<% end %>

<div class="row my-3" id="accordion-<%= feedback_message.id %>">
  <div class="card w-100">
    <div class="card-header" id="header<%= feedback_message.id %>">
      <a href="#" id="collapse__header__link-<%= feedback_message.id %>" data-toggle="collapse" data-target="#collapse<%= feedback_message.id %>" aria-expanded="true" aria-controls="collapse<%= feedback_message.id %>">
        Report #<%= feedback_message.id %> - Submitted: <%= time_ago_in_words feedback_message.created_at %> ago
      </a>
      <div class="float-right">
        ✉️ Emails Sent: <%= feedback_message_emails.size %> |
        <a href="/internal/reports/<%= feedback_message.id %>">Link to Report #<%= feedback_message.id %></a>
      </div>
    </div>
    <div id="collapse<%= feedback_message.id %>" class="collapse show" aria-labelledby="header<%= feedback_message.id %>" data-parent="#accordion-<%= feedback_message.id %>">
      <div class="card-body">
        <div class="row">
          <div class="col-9">
            <h2>
              Reporter:
            </h2>
            <h5>
              <% if feedback_message.reporter_id? %>
                <%= feedback_message.reporter.name %>
                <a href="<%= feedback_message.reporter.path %>">@<%= feedback_message.reporter.username %></a>
              <% else %>
                Anonymous
              <% end %>
            </h5>
            <h2>
              Reported URL (new tab):
            </h2>
            <h5>
              <a href="<%= feedback_message.reported_url %>" target="_blank" rel="noopener"><%= feedback_message.reported_url %></a>
            </h5>
          </div>
          <div class="col-3">
            <h3>
              <span class="badge badge-warning float-right"><%= feedback_message.category.titleize %></span>
            </h3>
          </div>
          <div class="col-12">
            <h2>
              Message:
            </h2>
            <p>
              <% if feedback_message.message.blank? %>
                <span class="font-italic">No message was left.</span>
              <% else %>
                <%= feedback_message.message %>
              <% end %>
            </p>
          </div>
        </div>
        <hr>
        <div class="row">
          <div class="col-12">
            <h2>Previous Emails:</h2>
            <div class="previous__emails__container">
              <% if feedback_message_emails.any? %>
                <% feedback_message_emails.each do |email| %>
                  <div class="email__container">
                    <p class="to__subject">Type: <%= email.utm_campaign.capitalize %></p>
                    <p class="to__subject">To: <%= email.to %></p>
                    <p class="to__subject">Subject: <%= email.subject %></p>
                    <%= email.body_html_content.html_safe %>
                  </div>
                <% end %>
              <% else %>
                <h5>No Email Records</h5>
              <% end %>
            </div>
          </div>
        </div>
        <hr>
        <div class="row">
          <div class="col-12">
            <h2>Email Form:</h2>
            <ul class="nav nav-tabs" role="tablist">
              <li role="presentation" class="nav-item">
                <a class="nav-link active" href="#reporter-<%= feedback_message.id %>" aria-controls="reporter-<%= feedback_message.id %>" role="tab" data-toggle="tab">Reporter</a>
              </li>
              <li role="presentation" class="nav-item">
                <a class="nav-link" href="#offender-<%= feedback_message.id %>" aria-controls="offender-<%= feedback_message.id %>" role="tab" data-toggle="tab">Offender</a>
              </li>
              <li role="presentation" class="nav-item">
                <a class="nav-link" href="#affected-<%= feedback_message.id %>" aria-controls="affected-<%= feedback_message.id %>" role="tab" data-toggle="tab">Affected</a>
              </li>
            </ul>
            <div class="tab-content my-3">
              <div role="tabcard" class="tab-pane fade active show" data-id="<%= feedback_message.id %>" data-userType="reporter" id="reporter-<%= feedback_message.id %>">
                <h3>Send To:</h3>
                <%= email_field_tag :reporter_email_to, feedback_message.reporter&.email, class: "form-control my-1", id: "reporter__emailto__#{feedback_message.id}", required: true %>
                <h3>Subject:</h3>
                <%= text_field_tag :reporter_email_subject, reporter_email_details[:subject], class: "form-control my-1", id: "reporter__subject__#{feedback_message.id}" %>
                <h3>Body:</h3>
                <%= text_area_tag :reporter_email_body, reporter_email_details[:body], class: "form-control my-1", style: "height: 300px;", id: "reporter__body__#{feedback_message.id}" %>
              </div>
              <div role="tabcard" class="tab-pane fade" data-id="<%= feedback_message.id %>" data-userType="offender" id="offender-<%= feedback_message.id %>">
                <h3>Send To:</h3>
                <%= email_field_tag :offender_email_to, feedback_message.offender&.email, class: "form-control my-1", id: "offender__emailto__#{feedback_message.id}", required: true %>
                <h3>Subject:</h3>
                <%= text_field_tag :offender_email_subject, offender_email_details[:subject], class: "form-control my-1", id: "offender__subject__#{feedback_message.id}" %>
                <h3>Body:</h3>
                <%= text_area_tag :offender_email_body, offender_email_details[:body], class: "form-control my-1", style: "height: 300px;", id: "offender__body__#{feedback_message.id}" %>
              </div>
              <div role="tabcard" class="tab-pane fade" data-id="<%= feedback_message.id %>" data-userType="affected" id="affected-<%= feedback_message.id %>">
                <h3>Send To:</h3>
                <%= email_field_tag :affected_email_to, feedback_message.affected&.email, class: "form-control my-1", id: "affected__emailto__#{feedback_message.id}", required: true %>
                <h3>Subject:</h3>
                <%= text_field_tag :affected_email_subject, affected_email_details[:subject], class: "form-control my-1", id: "affected__subject__#{feedback_message.id}" %>
                <h3>Body:</h3>
                <%= text_area_tag :affected_email_body, affected_email_details[:body], class: "form-control my-1", style: "height: 300px;", id: "affected__body__#{feedback_message.id}" %>
              </div>
            </div>
            <button class="btn btn-primary" type="button" id="send__email__btn__<%= feedback_message.id %>">Send Email ✉️</button>
          </div>
        </div>
        <div class="email__alert alert w-100 mt-2 d-none" id="email__alert__<%= feedback_message.id %>">
        </div>
        <div class="row my-3">
          <div class="col-12">
            <h3>Status:</h3>
            <%= f.select :status, %w[Open Invalid Resolved], {}, id: "status__#{feedback_message.id}" %>
            <button class="btn btn-primary d-block mt-3" type="button" id="save__status__<%= feedback_message.id %>">Save Status</button>
          </div>
        </div>
        <div class="row my-3">
          <div class="col-12">
            <h3>Notes:</h3>
            <div class="notes__container" id="notes__<%= feedback_message.id %>">
              <% feedback_message.notes&.order("created_at")&.each do |note| %>
                <div class="border border-info bg-light rounded my-2 p-2">
                  <span class="badge badge-info float-right">
                    <%= time_ago_in_words note.created_at %> ago
                  </span>
                  <h5 class="font-weight-bold">
                    <%= note.author.name %>:
                  </h5>
                  <p>
                    <%= note.content %>
                  </p>
                </div>
              <% end %>
            </div>
            <div>
              <input type="hidden" name="reason" value="<%= feedback_message.feedback_type %>" id="note__reason__<%= feedback_message.id %>">
              <input type="hidden" name="noteable_id" value="<%= feedback_message.id %>" id="note__noteable-id__<%= feedback_message.id %>">
              <input type="hidden" name="noteable_type" value="FeedbackMessage" id="note__noteable-type__<%= feedback_message.id %>">
              <input type="hidden" name="author_id" value="<%= current_user.id %>" id="note__author-id__<%= feedback_message.id %>">
              <input
                type="textarea"
                name="content"
                placeholder="Leave some notes about the status and context of this report."
                class="notefield"
                id="note__content__<%= feedback_message.id %>"
                required>
              <button class="btn btn-primary" type="button" id="note__submit__<%= feedback_message.id %>">Submit Note 📝</button>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-12 d-flex justify-content-end">
            <button class="btn btn-primary" type="button" id="minimize__report__button__<%= feedback_message.id %>">
              Minimize Report
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
 function saveStatus(id) {
   var formData = new FormData();
   var statusSelectTag = document.getElementById('status__' + id);
   var statusBtn = document.getElementById('save__status__' + id);
   formData.append('id', id);
   formData.append('status', statusSelectTag.options[statusSelectTag.selectedIndex].value);

   fetch('/internal/reports/save_status', {
     method: 'POST',
     headers: {
       'X-CSRF-Token': document.querySelector("meta[name='csrf-token']").content,
     },
     body: formData,
     credentials: 'same-origin'
   })
     .then(response => response.json()
                               .then(json => {
                                 if (json.outcome === 'Success') {
                                   console.log(json.outcome)
                                   statusBtn.innerText = "Saved!";
                                   setTimeout(function () {
                                     statusBtn.innerText = "Save Status"
                                   }, 1000);
                                 } else {
                                 }
                               }))
 }

 document.getElementById('save__status__' + <%= feedback_message.id %>).addEventListener('click', function (event) {
   event.preventDefault();
   var reportId = <%= feedback_message.id %>
     saveStatus(reportId);
 });

 function successfulEmail(alert) {
   alert.classList.remove("d-none");
   alert.classList.add('alert-success');
   alert.innerHTML = "Email sent successfully! Refresh to see";
 }

 function failedEmail(alert) {
   alert.classList.remove("d-none");
   alert.classList.add('alert-danger');
   alert.innerHTML = "Email failed to send, see console or Honeybadger for errors";
 }

 function sendEmail(id) {
   var activeTab = document.querySelector(".tab-pane.active[data-id='" + id + "']");
   var alert = document.getElementById('email__alert__' + id);
   var sendEmailBtn = document.getElementById('send__email__btn__' + id);
   var userType = activeTab.dataset.usertype;
   var emailToAddress = activeTab.querySelector("#" + userType + "__emailto__" + id).value;
   var subjectLine = activeTab.querySelector("#" + userType + "__subject__" + id).value;
   var emailBody = activeTab.querySelector("#" + userType + "__body__" + id).value;

   alert.classList.add("d-none");
   alert.classList.remove("alert-warning");
   alert.classList.remove("alert-success");
   alert.classList.remove("alert-danger");

   if (emailToAddress === "") {
     alert.classList.remove("d-none");
     alert.classList.add("alert-warning");
     alert.innerHTML = "Email can't be blank!"
     return
   }

   var formData = new FormData();
   formData.append('feedback_message_id', id);
   formData.append('email_to', emailToAddress);
   formData.append('email_body', emailBody);
   formData.append('email_subject', subjectLine);
   formData.append('email_type', userType);

   fetch('/internal/reports/send_email', {
     method: 'POST',
     headers: {
       'X-CSRF-Token': document.querySelector("meta[name='csrf-token']").content,
     },
     body: formData,
     credentials: 'same-origin'
   })
     .then(response => response.json()
                               .then(json => {
                                 if (json.outcome === "Success") {
                                   successfulEmail(alert);
                                 } else {
                                   console.log('email failed')
                                   failedEmail(alert);
                                 }
                               }))
     .catch(error => {
       failedEmail(alert);
       console.log(error);
     })
 }

 document.getElementById('send__email__btn__' + <%= feedback_message.id %>).addEventListener('click', function (event) {
   event.preventDefault();
   var reportId = <%= feedback_message.id %>;
   sendEmail(reportId);
 });

 function addNoteToPage(noteParams, id) {
   var notesDiv = document.getElementById('notes__' + id);

   var singleNoteDiv = document.createElement('div');
   singleNoteDiv.setAttribute('class', 'border border-info bg-light rounded my-2 p-2');

   var timeBadge = document.createElement('span');
   timeBadge.setAttribute('class', 'badge badge-info float-right');
   timeBadge.innerText = "just now";
   singleNoteDiv.append(timeBadge);

   var noteAuthor = document.createElement('H5');
   noteAuthor.setAttribute('class', 'font-weight-bold');
   var newNote = document.createElement('p');

   var authorContent = document.createTextNode(noteParams.author_name + ': ');
   var noteContent = document.createTextNode(noteParams.content);

   noteAuthor.appendChild(authorContent);
   newNote.appendChild(noteContent);

   singleNoteDiv.append(noteAuthor);
   singleNoteDiv.append(newNote);

   notesDiv.append(singleNoteDiv);
 }

 function clearNote(id) {
   document.getElementById('note__content__' + id).value = '';
 }

 function submitNote(id) {
   var formData = new FormData();
   formData.append('content', document.getElementById('note__content__' + id).value)
   formData.append('reason', document.getElementById('note__reason__' + id).value)
   formData.append('noteable_id', document.getElementById('note__noteable-id__' + id).value)
   formData.append('noteable_type', document.getElementById('note__noteable-type__' + id).value)
   formData.append('author_id', document.getElementById('note__author-id__' + id).value)

   fetch('/internal/reports/create_note', {
     method: 'POST',
     headers: {
       'X-CSRF-Token': document.querySelector("meta[name='csrf-token']").content,
     },
     body: formData,
     credentials: 'same-origin'
   })
           .then(response => response.json()
                                     .then(json => {
                                       if (json.outcome === 'Success') {
                                         addNoteToPage(json, id);
                                         clearNote(id);
                                       } else {
                                         // failedNote();
                                       }
                                     })
                                     .catch(error => {
                                       // failedNote();
                                       console.log(error);
                                     }))
 }

 document.getElementById('note__submit__<%= feedback_message.id %>').addEventListener('click', function () {
   var reportId = <%= feedback_message.id %>;
   submitNote(reportId);
 });

 document.getElementById('minimize__report__button__<%= feedback_message.id %>').addEventListener('click', function () {
   document.getElementById('collapse__header__link-<%= feedback_message.id %>').click();
 });
</script>
