{% extends "layouts/base.html" %}
{% load crispy_forms_tags %}
{% load i18n %}
{% load month_name %}
{% load static %}

{% block title %}{% translate 'Monthly Overview' %} :: {{ month|month_name }}/{{ year }}{% endblock %}

{% block body_hyperscript %}
  on keyup[code is 'ArrowLeft' and target.nodeName is 'BODY'] from body trigger 'previous_month' end
  on keyup[code is 'ArrowRight' and target.nodeName is 'BODY'] from body trigger 'next_month' end
{% endblock %}

{% block content %}
  <div class="container gap-y-3">
    <div class="row mt-7 mb-5">
      <div class="col-12 lg:col-4">
        {#    Date picker#}
        <div class="flex flex-row items-center">
          <a role="button"
             class="btn btn-ghost"
            hx-boost="true"
            hx-trigger="click, previous_month from:window"
            href="{% url 'monthly_overview' month=previous_month year=previous_year %}">
            <i class="fa-solid fa-chevron-left"></i>
          </a>
          <div class="text-2xl font-bold btn btn-ghost flex-1 text-center whitespace-normal flex-wrap h-auto min-w-0"
              hx-get="{% url 'month_year_picker' %}"
              hx-target="#generic-offcanvas-left"
              hx-trigger="click, date_picker from:window"
              hx-vals='{"month": {{ month }}, "year": {{ year }}, "for": "monthly_overview", "field": "reference_date"}'
              role="button">
            {{ month|month_name }} {{ year }}
          </div>
          <a role="button"
             class="btn btn-ghost"
            hx-boost="true"
            hx-trigger="click, next_month from:window"
            href="{% url 'monthly_overview' month=next_month year=next_year %}">
            <i class="fa-solid fa-chevron-right"></i>
          </a>
        </div>
      </div>
    </div>
    {#  Monthly summary#}
    <div class="row gap-y-3">
      <div class="col-12 lg:col-4 lg:order-last! order-first!">
        <div role="tablist" class="tabs tabs-border">
          <input type="radio" name="monthly_summary_tabs" class="tab" aria-label="{% trans 'Summary' %}"
                 role="tab"
                 {% if summary_tab == 'summary' or not summary_tab %}checked="checked"{% endif %}
                 _="on click fetch {% url 'monthly_summary_select' selected='summary' %}"
                 aria-controls="summary-tab-pane"/>
          <div class="tab-content" id="summary-tab-pane" role="tabpanel">
            <div id="summary"
                 hx-get="{% url 'monthly_summary' month=month year=year %}"
                 class="show-loading"
                 hx-trigger="load, updated from:window, selective_update from:window, every 10m"
                 hx-include="#filter">
            </div>
          </div>

          <input type="radio" name="monthly_summary_tabs" class="tab" aria-label="{% trans 'Currencies' %}"
                 role="tab"
                 {% if summary_tab == 'currency' %}checked="checked"{% endif %}
                 _="on click fetch {% url 'monthly_summary_select' selected='currency' %}"
                 aria-controls="currency-tab-pane" />
          <div class="tab-content" id="currency-tab-pane" role="tabpanel">
            <div id="currency-summary"
                 hx-get="{% url 'monthly_currency_summary' month=month year=year %}"
                 class="show-loading"
                 hx-trigger="load, updated from:window, selective_update from:window, every 10m"
                 hx-include="#filter">
            </div>
          </div>

          <input type="radio" name="monthly_summary_tabs" class="tab" aria-label="{% trans 'Accounts' %}"
                 role="tab"
                 {% if summary_tab == 'account' %}checked="checked"{% endif %}
                 _="on click fetch {% url 'monthly_summary_select' selected='account' %}"
                 aria-controls="account-tab-pane" />
          <div class="tab-content" id="account-tab-pane" role="tabpanel">
            <div id="account-summary"
                 hx-get="{% url 'monthly_account_summary' month=month year=year %}"
                 class="show-loading"
                 hx-trigger="load, updated from:window, selective_update from:window, every 10m"
                 hx-include="#filter">
            </div>
          </div>
        </div>

      </div>
      <div class="col-12 lg:col-8 lg:order-first! order-last!">

        <div class="my-3" x-data="{ filterOpen: false }" hx-preserve id="filter-container">
          {# Hidden select to hold the order value and preserve the original update trigger #}
          <select name="order" id="order" class="d-none" _="on change trigger updated on window">
            <option value="default" {% if order == 'default' %}selected{% endif %}>{% translate 'Default' %}</option>
            <option value="older" {% if order == 'older' %}selected{% endif %}>{% translate 'Oldest first' %}</option>
            <option value="newer" {% if order == 'newer' %}selected{% endif %}>{% translate 'Newest first' %}</option>
          </select>

          {# Main control bar with filter, search, and ordering #}
          <div class="join w-full">

            <button class="btn btn-secondary join-item relative z-1" type="button"
                    @click="filterOpen = !filterOpen"
                    :aria-expanded="filterOpen" id="filter-button"
                    title="{% translate 'Filter transactions' %}"
                    _="on load or change from #filter
                         -- Check if any filter has a non-default value
                         set hasActiveFilter to false

                         -- Check type (default is both IN and EX checked)
                         set typeInputs to <input[name='type']:checked/> in #filter
                         if typeInputs.length is not 2
                           set hasActiveFilter to true
                         end

                         -- Check is_paid (default is both 1 and 0 checked)
                         set isPaidInputs to <input[name='is_paid']:checked/> in #filter
                         if isPaidInputs.length is not 2
                           set hasActiveFilter to true
                         end

                         -- Check mute_status (default is both active and muted checked)
                         set muteStatusInputs to <input[name='mute_status']:checked/> in #filter
                         if muteStatusInputs.length is not 2
                           set hasActiveFilter to true
                         end

                         -- Check description
                         set descInput to #id_description
                         if descInput exists and descInput.value is not ''
                           set hasActiveFilter to true
                         end

                         -- Check date_start
                         set dateStartInput to #id_date_start
                         if dateStartInput exists and dateStartInput.value is not ''
                           set hasActiveFilter to true
                         end

                         -- Check date_end
                         set dateEndInput to #id_date_end
                         if dateEndInput exists and dateEndInput.value is not ''
                           set hasActiveFilter to true
                         end

                         -- Check reference_date_start
                         set refDateStartInput to #id_reference_date_start
                         if refDateStartInput exists and refDateStartInput.value is not ''
                           set hasActiveFilter to true
                         end

                         -- Check reference_date_end
                         set refDateEndInput to #id_reference_date_end
                         if refDateEndInput exists and refDateEndInput.value is not ''
                           set hasActiveFilter to true
                         end

                         -- Check from_amount
                         set fromAmountInput to #id_from_amount
                         if fromAmountInput exists and fromAmountInput.value is not ''
                           set hasActiveFilter to true
                         end

                         -- Check to_amount
                         set toAmountInput to #id_to_amount
                         if toAmountInput exists and toAmountInput.value is not ''
                           set hasActiveFilter to true
                         end

                         -- Check account (TomSelect stores values differently)
                         set accountInput to #id_account
                         if accountInput exists and accountInput.value is not ''
                           set hasActiveFilter to true
                         end

                         -- Check currency
                         set currencyInput to #id_currency
                         if currencyInput exists and currencyInput.value is not ''
                           set hasActiveFilter to true
                         end

                         -- Check category
                         set categoryInput to #id_category
                         if categoryInput exists and categoryInput.value is not ''
                           set hasActiveFilter to true
                         end

                         -- Check tags
                         set tagsInput to #id_tags
                         if tagsInput exists and tagsInput.value is not ''
                           set hasActiveFilter to true
                         end

                         -- Check entities
                         set entitiesInput to #id_entities
                         if entitiesInput exists and entitiesInput.value is not ''
                           set hasActiveFilter to true
                         end

                         -- Show or hide the indicator
                         if hasActiveFilter
                           remove .hidden from #filter-active-indicator
                         else
                           add .hidden to #filter-active-indicator
                         end">
              <i class="fa-solid fa-filter fa-fw"></i>
              <span id="filter-active-indicator" class="absolute -top-1 -right-1 w-3 h-3 bg-error rounded-full hidden z-10"></span>
            </button>

            {# Search box #}
            <label for="quick-search" class="hidden">
            </label>
            <input type="search"
                   class="input input-bordered join-item flex-1"
                   placeholder="{% translate 'Search' %}"
                   id="quick-search"
                   _="on input or search or htmx:afterSwap from window
                         if my value is empty
                           trigger toggle on <.transactions-divider-collapse/>
                         else
                           trigger show on <.transactions-divider-collapse/>
                         end
                         show <.transactions-divider-title/> when my value is empty
                         show <.transaction/> in <#transactions-list/>
                         when its textContent.toLowerCase() contains my value.toLowerCase()">

            {# Order by icon dropdown #}
            <div>
              <button class="btn btn-secondary join-item" type="button"
                      data-bs-toggle="dropdown" aria-expanded="false"
                      title="{% translate 'Order by' %}">
                <i class="fa-solid fa-sort fa-fw"></i>
              </button>
              <ul class="dropdown-menu dropdown-menu-end menu">
                <li>
                  <button class="{% if order == 'default' %}menu-active{% endif %}" type="button"
                          _="on click remove .menu-active from <li > button/> in the closest <ul/>
                            then add .menu-active to me
                            then set the value of #order to 'default'
                            then trigger change on #order">
                    {% translate 'Default' %}
                  </button>
                </li>
                <li>
                  <button class="{% if order == 'older' %}menu-active{% endif %}" type="button"
                          _="on click remove .menu-active from <li > button/> in the closest <ul/>
                            then add .menu-active to me
                            then set the value of #order to 'older'
                            then trigger change on #order">
                    {% translate 'Oldest first' %}
                  </button>
                </li>
                <li>
                  <button class="{% if order == 'newer' %}menu-active{% endif %}" type="button"
                          _="on click remove .menu-active from <li > button/> in the closest <ul/>
                            then add .menu-active to me
                            then set the value of #order to 'newer'
                            then trigger change on #order">
                    {% translate 'Newest first' %}
                  </button>
                </li>
              </ul>
            </div>
          </div>

          {# Filter transactions form #}
          <div class="z-1" x-show="filterOpen" x-collapse>
            <div class="card card-body bg-base-200 mt-2">
              <div class="text-right">
                <button class="btn btn-outline btn-error btn-sm w-fit"
                        _="on click call #filter.reset() then trigger change on #filter">{% translate 'Clear' %}</button>
              </div>

              <form _="on change or submit or search trigger updated on window
                         install init_tom_select
                         install init_datepicker"
                    id="filter" class="mt-3">
                {% crispy filter.form %}
              </form>

              <div class="text-right">
                <button class="btn btn-outline btn-error btn-sm w-fit"
                        _="on click call #filter.reset() then trigger change on #filter">{% translate 'Clear' %}</button>
              </div>
            </div>
          </div>
        </div>
        {#      Transactions list#}
        <div id="transactions"
             class="show-loading"
             hx-get="{% url 'monthly_transactions_list' month=month year=year %}"
             hx-trigger="load, updated from:window, every 10m" hx-include="#filter, #order">
        </div>
      </div>
    </div>
  </div>

  <c-ui.transactions_fab></c-ui.transactions_fab>

{% endblock %}
