{% extends "deliver_grant_funding/grant_base.html" %}
{% from "govuk_frontend_jinja/components/summary-list/macro.html" import govukSummaryList %}
{% from "govuk_frontend_jinja/components/table/macro.html" import govukTable %}
{% from "govuk_frontend_jinja/components/tag/macro.html" import govukTag %}
{% from "govuk_frontend_jinja/components/notification-banner/macro.html" import govukNotificationBanner %}
{% from "deliver_grant_funding/macros/deliver_grant_funding_collection_breadcrumb.html" import deliver_grant_funding_collection_breadcrumb %}
{% from "govuk_frontend_jinja/components/warning-text/macro.html" import govukWarningText %}
{% from "govuk_frontend_jinja/components/details/macro.html" import govukDetails %}

{% set type_constants = collection.type.constants %}
{% set active_item_identifier = type_constants.active_nav %}
{% set page_title = data_source.name %}

{% block beforeContent %}
  {{ deliver_grant_funding_collection_breadcrumb(grant=grant, data_set=data_source, this_page_breadcrumb_item={"text": data_source.name}) }}
{% endblock beforeContent %}

{% block content %}
  <div class="govuk-grid-row">
    <div class="govuk-grid-column-two-thirds">
      {% with flashes = get_flashed_messages(category_filter=[enum.flash_message_type.DATA_SOURCE_REPLACED_SUCCESS]) %}
        {% if flashes %}
          {% set success_message %}
            <h3 class="govuk-notification-banner__heading">{{ data_source.name }} data set replaced</h3>
            <p class="govuk-body">{{ flashes[0] }}</p>
          {% endset %}
          {{
            govukNotificationBanner({
              "html": success_message, "type": "success"
            })
          }}
        {% endif %}
      {% endwith %}
      {% with flashes = get_flashed_messages(category_filter=[enum.flash_message_type.DATA_SOURCE_REFERENCE_ERROR.value]) %}
        {% for flash in flashes %}
          {% set reference_error_html %}
            <p class="govuk-body govuk-!-font-weight-bold">{{ flash.message }}</p>
            {% for ref in flash.references %}
              {% set component_link = url_for("deliver_grant_funding.edit_question", grant_id=flash.grant_id, question_id=ref.component_id) if not ref.is_group else url_for("deliver_grant_funding.list_group_questions", grant_id=flash.grant_id, group_id=ref.component_id) %}
              <p class="govuk-body govuk-!-font-weight-bold">
                <a class="govuk-notification-banner__link" href="{{ component_link }}">{{ interpolate(ref.component_text) }} ({{ ref.reference_type }})</a>
              </p>
            {% endfor %}
          {% endset %}
          {{
            govukNotificationBanner(params={
              "role": "alert",
              "titleText": "Error",
              "classes": "app-notification-banner--destructive",
              "html": reference_error_html,
            })
          }}
        {% endfor %}
      {% endwith %}

      {% if delete_form and authorisation_helper.can_edit_collection(current_user, collection.id) %}
        {% set banner_html %}
          <p class="govuk-body govuk-!-font-weight-bold">Are you sure you want to delete this data set?</p>
          <form method="post" novalidate>
            {{ delete_form.csrf_token }}
            <div class="govuk-button-group govuk-!-margin-bottom-0">
              {{ delete_form.confirm_deletion(params={"text": "Yes, delete this data set", "classes": "govuk-button--warning govuk-!-margin-bottom-0"}) }}
              <a
                class="govuk-link govuk-link--no-visited-state govuk-!-margin-bottom-0"
                href="{{ url_for('deliver_grant_funding.view_data_source', grant_id=grant.id, collection_type=collection.type, collection_id=collection.id, data_source_id=data_source.id) }}"
                >Cancel
              </a>
            </div>
          </form>
        {% endset %}

        {{ govukNotificationBanner(params={"role": "alert", "titleText": "Important", "classes": "", "html": banner_html}) }}
      {% endif %}

      <h1 class="govuk-heading-l">
        <span class="govuk-caption-l">{{ collection.name }}</span>
        {{ data_source.name }}
      </h1>

      {% set data_set_html %}
        {{ data_source.file_metadata.original_filename }}
        <br />
        <a
          class="govuk-link govuk-link--no-visited-state"
          href="{{ url_for('deliver_grant_funding.download_data_source_csv', grant_id=grant.id, collection_type=collection.type, collection_id=collection.id, data_source_id=data_source.id) }}">
          Download data set (CSV)
        </a>
      {% endset %}


      {% set uploaded_time %}
        <time datetime="{{ iso_utc(data_source.updated_at_utc) }}">{{ format_datetime_short(data_source.updated_at_utc) }}</time>
      {% endset %}

      {%
        set summary_rows = [
          {
            "key": {"text": "Uploaded by"},
            "value": {"text": data_source.updated_by.name if data_source.updated_by else data_source.created_by.name}
          },
          {
            "key": {"text": "Date and time uploaded"},
            "value": {"html": uploaded_time},
          },
          {
            "key": {"text": "Uploaded data set"},
            "value": {"html": data_set_html}
          }
        ]
      %}

      {{ govukSummaryList({"rows": summary_rows}) }}

      {% if has_missing_data and not added_grant_recipient_names %}
        {{ govukWarningText({"text": ("Grant recipients with missing data will not be able to complete the report until their missing data is uploaded.")}) }}
      {% elif has_missing_data and added_grant_recipient_names %}
        {% set missing_data_added_recipients_html %}
          Grant recipients not in the data set and missing data will not be able to access their report until their missing data is uploaded.
          <a
            class="govuk-link govuk-link--no-visited-state"
            href="{{ url_for('deliver_grant_funding.download_latest_data_set_template', grant_id=grant.id, collection_type=collection.type, collection_id=collection.id, data_source_id=data_source.id) }}"
            >Download the latest data set template (CSV)</a
          >
          to replace this data set.
        {% endset %}
        {{ govukWarningText({"html": missing_data_added_recipients_html}) }}
      {% endif %}

      {% if removed_grant_recipient_names and not has_missing_data %}
        <div class="govuk-body">
          <a
            class="govuk-link govuk-link--no-visited-state"
            href="{{ url_for('deliver_grant_funding.download_latest_data_set_template', grant_id=grant.id, collection_type=collection.type, collection_id=collection.id, data_source_id=data_source.id) }}"
            >Download the latest data set template (CSV)</a
          >
          to update and replace this data set.
        </div>
      {% endif %}

      {% if added_grant_recipient_names or removed_grant_recipient_names %}
        {% set grant_recipient_changes_html %}
          <p class="govuk-body">Grant recipients have been updated for this grant since the latest file was uploaded.</p>
          {% if added_grant_recipient_names %}
            <p class="govuk-body">Grant recipients added:</p>
            <ul class="govuk-list govuk-list--bullet">
              {% for name in added_grant_recipient_names %}
                <li>{{ name }}</li>
              {% endfor %}
            </ul>
          {% endif %}
          {% if removed_grant_recipient_names %}
            <p class="govuk-body">Grant recipients removed:</p>
            <ul class="govuk-list govuk-list--bullet">
              {% for name in removed_grant_recipient_names %}
                <li>{{ name }}</li>
              {% endfor %}
            </ul>
          {% endif %}
        {% endset %}
        {{
          govukDetails({
            "summaryText": "Grant recipient changes",
            "html": grant_recipient_changes_html,
          })
        }}
      {% endif %}

      <div class="govuk-button-group">
        {% if authorisation_helper.can_replace_dataset(current_user, collection.id) %}
          <a class="govuk-button govuk-button--secondary" href="{{ url_for('deliver_grant_funding.replace_data_set', grant_id=grant.id, collection_id=collection.id, collection_type=collection.type, data_source_id=data_source.id) }}">
            Replace data set
          </a>
        {% endif %}
        {% if authorisation_helper.can_edit_collection(current_user, collection.id) %}
          <a class="govuk-button govuk-button--warning" href="?delete">Delete data set</a>
        {% endif %}
      </div>
    </div>

    <div class="govuk-grid-column-full">
      <h2 class="govuk-heading-m">Data columns</h2>
      {%
        set head = [
          {"text": constants.data_set_external_id_column_header},
          {"text": constants.data_set_grant_recipient_column_header}
        ]
      %}
      {% for slug, col_schema in data_source.schema.ordered_items() %}
        {% do head.append({"text": col_schema.original_column_name}) %}
      {% endfor %}

      {% set rows = [] %}
      {% for current_row in current_rows %}
        {% set row = [{"text": current_row.external_id}] %}

        {% if current_row.organisation_item is none %}
          {% do row.append({"html": govukTag({"text": "Grant recipient missing", "classes": "govuk-tag--red app-status-tag"}) ~ " " ~ current_row.grant_recipient_name}) %}
        {% else %}
          {% do row.append({"text": current_row.grant_recipient_name}) %}
        {% endif %}

        {% set typed_row = current_row.organisation_item.data if current_row.organisation_item else {} %}
        {% for slug, col_schema in data_source.schema.ordered_items() %}
          {% set answer = typed_row.get(slug) %}
          {% if answer is none %}
            {% do row.append({"html": govukTag({"text": "Data missing", "classes": "govuk-tag--orange"})}) %}
          {% else %}
            {% do row.append({"text": answer.get_value_for_interpolation()}) %}
          {% endif %}
        {% endfor %}
        {% do rows.append(row) %}
      {% endfor %}

      <div class="moj-scrollable-pane" role="region" aria-label="{{ data_source.name }}" tabindex="0">{{ govukTable({"head": head, "rows": rows}) }}</div>
    </div>
  </div>
{% endblock content %}
