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

{% block title %}{% if type == "current" %}{% translate 'Current Net Worth' %}{% else %}{% translate 'Projected Net Worth' %}{% endif %}{% endblock %}

{% block content %}
  <div class="container px-md-3 py-3" _="init call initializeAccountChart() then initializeCurrencyChart() end">
    <div class="row gx-xl-4 gy-3 mb-4">
      <div class="col-12 col-xl-5">
        <div class="row row-cols-1 g-4">
          <div class="col">
            <c-ui.info-card color="yellow" icon="fa-solid fa-coins" title="{% trans 'By currency' %}"
                            _="on click showAllDatasetsCurrency()">
              {% for currency in currency_net_worth.values %}
                <div class="d-flex justify-content-between mt-2">
                  <div class="d-flex align-items-baseline w-100">
                    <div class="currency-name text-start font-monospace tw-text-gray-300"
                         _="on click showOnlyCurrencyDataset('{{ currency.currency.name }}')">
                      {{ currency.currency.name }}
                    </div>
                    <div class="dotted-line flex-grow-1"></div>
                    <div>
                      <c-amount.display
                          :amount="currency.total_final"
                          :prefix="currency.currency.prefix"
                          :suffix="currency.currency.suffix"
                          :decimal_places="currency.currency.decimal_places"
                          color="{% if currency.total_final > 0 %}green{% elif currency.total_final < 0 %}red{% endif %}"
                          text-end></c-amount.display>
                    </div>
                  </div>
                </div>
                {% if currency.exchanged and currency.exchanged.total_final %}
                  <div>
                    <c-amount.display
                        :amount="currency.exchanged.total_final"
                        :prefix="currency.exchanged.currency.prefix"
                        :suffix="currency.exchanged.currency.suffix"
                        :decimal_places="currency.exchanged.currency.decimal_places"
                        text-end
                        color="grey"></c-amount.display>
                  </div>
                {% endif %}
                {% if currency.consolidated %}
                  <div class="d-flex align-items-baseline w-100">
                        <div class="account-name text-start font-monospace tw-text-gray-300">
                          <span class="hierarchy-line-icon"></span>{% trans 'Consolidated' %}</div>
                        <div class="dotted-line flex-grow-1"></div>
                        <div class="">
                          <c-amount.display
                            :amount="currency.consolidated.total_final"
                            :prefix="currency.consolidated.currency.prefix"
                            :suffix="currency.consolidated.currency.suffix"
                            :decimal_places="currency.consolidated.currency.decimal_places"
                            color="{% if currency.total_final > 0 %}green{% elif currency.total_final < 0 %}red{% endif %}"
                            text-end></c-amount.display>
                        </div>
                      </div>
                {% endif %}
              {% endfor %}
            </c-ui.info-card>
          </div>
        </div>
      </div>
      <div class="col-12 col-xl-7">
        <div class="chart-container position-relative tw-min-h-[40vh] tw-h-full">
          <canvas id="currencyBalanceChart"></canvas>
        </div>
      </div>
    </div>
    <hr>
    <div class="row gx-xl-4 gy-3 mt-4">
      <div class="col-12 col-xl-5">
        <div class="row row-cols-1 g-4">
          <div class="col">
            <c-ui.info-card color="blue" icon="fa-solid fa-wallet" title="{% trans 'By account' %}"
                            _="on click showAllDatasetsAccount()">
              {% regroup account_net_worth.values by account.group as account_data %}
              {% for data in account_data %}
                {% if data.grouper %}
                  <div class="d-flex justify-content-between mt-2">
                    <div class="d-flex align-items-baseline w-100">
                      <div class="text-start font-monospace tw-text-gray-300"><span class="badge text-bg-primary">
                        {{ data.grouper }}</span></div>
                    </div>
                  </div>
                  {% for account in data.list %}
                    <div class="d-flex justify-content-between mt-2">
                      <div class="d-flex align-items-baseline w-100">
                        <div class="account-name text-start font-monospace tw-text-gray-300"
                             _="on click showOnlyAccountDataset('{{ account.account.name }}')">
                          <span class="hierarchy-line-icon"></span>{{ account.account.name }}</div>
                        <div class="dotted-line flex-grow-1"></div>
                        <div class="">
                          <c-amount.display
                              :amount="account.total_final"
                              :prefix="account.currency.prefix"
                              :suffix="account.currency.suffix"
                              :decimal_places="account.currency.decimal_places"
                              color="{% if account.total_final > 0 %}green{% elif account.total_final < 0 %}red{% endif %}"></c-amount.display>
                        </div>
                      </div>
                    </div>
                    {% if account.exchanged and account.exchanged.total_final %}
                      <c-amount.display
                          :amount="account.exchanged.total_final"
                          :prefix="account.exchanged.currency.prefix"
                          :suffix="account.exchanged.currency.suffix"
                          :decimal_places="account.exchanged.currency.decimal_places"
                          color="grey"
                          text-end></c-amount.display>
                    {% endif %}
                  {% endfor %}
                {% else %}
                  {% for account in data.list %}
                    <div class="d-flex justify-content-between mt-2">
                      <div class="d-flex align-items-baseline w-100">
                        <div class="account-name text-start font-monospace tw-text-gray-300"
                             _="on click showOnlyAccountDataset('{{ account.account.name }}')">
                          {{ account.account.name }}
                        </div>
                        <div class="dotted-line flex-grow-1"></div>
                        <div>
                          <c-amount.display
                              :amount="account.total_final"
                              :prefix="account.currency.prefix"
                              :suffix="account.currency.suffix"
                              :decimal_places="account.currency.decimal_places"
                              color="{% if account.total_final > 0 %}green{% elif account.total_final < 0 %}red{% endif %}"></c-amount.display>
                        </div>
                      </div>
                    </div>
                    {% if account.exchanged and account.exchanged.total_final %}
                      <c-amount.display
                          :amount="account.exchanged.total_final"
                          :prefix="account.exchanged.currency.prefix"
                          :suffix="account.exchanged.currency.suffix"
                          :decimal_places="account.exchanged.currency.decimal_places"
                          color="grey"
                          text-end></c-amount.display>
                    {% endif %}
                  {% endfor %}
                {% endif %}
              {% endfor %}
            </c-ui.info-card>
          </div>
        </div>
      </div>
      <div class="col-12 col-xl-7">
        <div class="chart-container position-relative tw-min-h-[40vh] tw-h-full">
          <canvas id="accountBalanceChart"></canvas>
        </div>
      </div>
    </div>
  </div>

  <script>
      var currencyChart;

      function initializeCurrencyChart() {
          // Destroy existing chart if it exists
          if (currencyChart) {
              currencyChart.destroy();
          }

          var chartData = JSON.parse('{{ chart_data_currency_json|safe }}');
          var currencies = {{ currencies|safe }};
          var ctx = document.getElementById('currencyBalanceChart').getContext('2d');

          currencyChart = new Chart(ctx, {
              type: 'line',
              data: chartData,
              options: {
                  maintainAspectRatio: false,
                  responsive: true,
                  interaction: {
                      mode: 'index',
                      intersect: false,
                  },
                  plugins: {
                      title: {
                          display: true,
                          text: '{% translate 'Evolution by currency' %}'
                      },
                      tooltip: {
                          mode: 'index',
                          intersect: false
                      }
                  },
                  scales: {
                      x: {
                          display: true,
                          title: {
                              display: false,
                          }
                      },
                      ...Object.fromEntries(currencies.map((currency, i) => [
                          `y${i}`,
                          {
                              type: 'linear',
                              display: true,
                              grid: {
                                  drawOnChartArea: i === 0,
                              },
                              ticks: {
                                  display: false,
                                  format: {maximumFractionDigits: 40, minimumFractionDigits: 0}
                              },
                              border: {
                                  display: false
                              }
                          }
                      ]))
                  }
              }
          });
      }
  </script>

  <script id="accountBalanceChartScript">
      var accountChart;

      function initializeAccountChart() {
          // Destroy existing chart if it exists
          if (accountChart) {
              accountChart.destroy();
          }

          var chartData = JSON.parse('{{ chart_data_accounts_json|safe }}');
          var accounts = {{ accounts|safe }};
          var ctx = document.getElementById('accountBalanceChart').getContext('2d');

          accountChart = new Chart(ctx, {
              type: 'line',
              data: chartData,
              options: {
                  maintainAspectRatio: false,
                  responsive: true,
                  interaction: {
                      mode: 'index',
                      intersect: false,
                  },
                  stacked: false,
                  plugins: {
                      title: {
                          display: true,
                          text: '{% translate "Evolution by account" %}'
                      },
                      tooltip: {
                          mode: 'index',
                          intersect: false
                      }
                  },
                  scales: {
                      x: {
                          display: true,
                          title: {
                              display: false,
                          }
                      },
                      ...Object.fromEntries(accounts.map((account, i) => [
                          `y-axis-${i}`,
                          {
                              type: 'linear',
                              display: true,
                              position: i % 2 === 0 ? 'left' : 'right',
                              grid: {
                                  drawOnChartArea: i === 0,
                              },
                              ticks: {
                                  display: false,
                                  format: {maximumFractionDigits: 40, minimumFractionDigits: 0}
                              },
                              border: {
                                  display: false
                              }
                          }
                      ]))
                  }
              }
          });
      }
  </script>

  <script type="text/hyperscript">
    def showOnlyAccountDataset(datasetName)
      for dataset in accountChart.data.datasets
        set isMatch to dataset.label is datasetName
        call accountChart.setDatasetVisibility(accountChart.data.datasets.indexOf(dataset), isMatch)
      end
      call accountChart.update()
    end

    def showOnlyCurrencyDataset(datasetName)
      for dataset in currencyChart.data.datasets
        set isMatch to dataset.label is datasetName
        call currencyChart.setDatasetVisibility(currencyChart.data.datasets.indexOf(dataset), isMatch)
      end
      call currencyChart.update()
    end

    def showAllDatasetsAccount()
      for dataset in accountChart.data.datasets
        call accountChart.setDatasetVisibility(accountChart.data.datasets.indexOf(dataset), true)
      end
      call accountChart.update()
    end

    def showAllDatasetsCurrency()
      for dataset in currencyChart.data.datasets
        call currencyChart.setDatasetVisibility(currencyChart.data.datasets.indexOf(dataset), true)
      end
      call currencyChart.update()
    end
  </script>

{% endblock %}
