{% extends "deliver_grant_funding/base.html" %}
{% from "govuk_frontend_jinja/components/button/macro.html" import govukButton %}
{% from "govuk_frontend_jinja/components/table/macro.html" import govukTable %}
{% from "common/macros/status.html" import grantStatusTag with context %}

{% set page_title = "Grants" %}
{% set active_item_identifier = "grants" %}

{% set onboarding_grants = grants | selectattr("status", "in", [enum.grant_status.LIVE, enum.grant_status.ONBOARDING]) | list %}
{% set draft_grants = grants | selectattr("status", "equalto", enum.grant_status.DRAFT) | list %}

{% block content %}
  <div class="govuk-grid-row">
    <div class="govuk-grid-column-two-thirds">
      <h1 class="govuk-heading-l">Grants</h1>
      {% if authorisation_helper.is_deliver_org_member(current_user) %}
        {{
          govukButton({
            "text": "Set up a grant",
            "href": url_for("deliver_grant_funding.grant_setup_intro"),
            "classes": "govuk-button--secondary" if ((onboarding_grants + draft_grants) | length) else ""
          })
        }}
      {% endif %}
    </div>
  </div>
  <div class="govuk-grid-row">
    <div class="govuk-grid-column-full govuk-!-margin-top-4">
      {% if onboarding_grants %}
        <div class="govuk-!-margin-bottom-8">
          <h2 class="govuk-heading-m">Active grants</h2>
          {{ grant_table(onboarding_grants, id_override="active-grants") }}
        </div>
      {% endif %}

      {% if draft_grants %}
        <div class="govuk-!-margin-bottom-8">
          <h2 class="govuk-heading-m">Draft grants</h2>
          {{ grant_table(draft_grants, id_override="draft-grants") }}
        </div>
      {% endif %}

      {% if not onboarding_grants and not draft_grants %}
        <p class="govuk-body">You have access to no grants.</p>
      {% endif %}
    </div>
  </div>
{% endblock content %}

{% macro grant_table(grants, id_override=none) %}
  {% set table_rows = namespace(items=[]) %}
  {% for grant in grants %}
    {% set grant_homepage_link %}
      <a class="govuk-link govuk-link--no-visited-state" href="{{ url_for('deliver_grant_funding.grant_homepage', grant_id=grant.id) }}">{{ grant.name }}</a>
    {% endset %}
    {%
      set table_rows.items = table_rows.items + [
          [{"html": grant_homepage_link},
            {"text": grant.ggis_number},
            {"text": grantStatusTag(grant.status)}]
      ]
    %}
  {% endfor %}

  {{
    govukTable({
        "captionClasses": "govuk-table__caption--m",
        "firstCellIsHeader": false,
        "head": [{"text": "Grant"}, {"text": "GGIS number", "classes": "app-!-cell-width-300"}, {"text": "Status", "classes": "app-!-cell-width-200"}],
        "rows": table_rows.items,
        "attributes": {"id": id_override},
    })
  }}
{% endmacro %}
