{% extends "fleetfinder/base.html" %}

{% load aa_i18n %}
{% load i18n %}

{% block aa_fleetfinder_body %}
    <div class="card card-default border-0">
        <div class="card-header card-default">
            <div class="card-title mb-0">
                {% translate "Fleets available to you" %}
            </div>
        </div>

        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped table-hover table-vertical-middle" id="table_available-fleets" style="width: 100%;">
                    <thead>
                        <tr>
                            <th>{% translate "Fleet commander" %}</th>
                            <th>{% translate "Fleet name" %}</th>
                            <th>{% translate "Created at" %}</th>
                            <th class="text-end"><!-- {% translate "Join" %} --></th>
                        </tr>
                    </thead>

                    <tbody></tbody>
                </table>
            </div>
        </div>
    </div>
{% endblock %}

{% block extra_css %}
    {% include "bundles/datatables-css-bs5.html" %}
    {% include "fleetfinder/bundles/css/fleetfinder-css.html" %}
{% endblock %}

{% block extra_javascript %}
    {% include "bundles/datatables-js-bs5.html" %}
    {% include "bundles/moment-js.html" with locale=True %}
    {% include "fleetfinder/bundles/js/fleetfinder-js.html" %}

    {% get_datatables_language_static LANGUAGE_CODE as DT_LANG_PATH %}

    <script>
        /* global fetchGet, fleetfinderBootstrapTooltip, DataTable */
        'use strict';

        $(document).ready(() => {
            const DATETIME_FORMAT = 'YYYY-MM-DD, HH:mm';
            const table_fleet_overview = $('#table_available-fleets');
            let dataTable = null;

            /**
             * Initialize or update the datatable.
             * If the table already exists, it will be updated with new data.
             * If it does not exist, a new DataTable will be created.
             *
             * @param {Object} data - The fleet data to populate the table.
             */
            const initializeOrUpdateTable = (data) => {
                if (dataTable) {
                    // Update existing table
                    dataTable.clear().rows.add(data).draw();
                } else {
                    // Initialize new table
                    dataTable = table_fleet_overview.DataTable({
                        language: {
                            url: '{{ DT_LANG_PATH }}'
                        },
                        data: data,
                        columns: [
                            {
                                data: 'fleet_commander',
                                render: {
                                    _: 'html',
                                    sort: 'sort'
                                }
                            },
                            {
                                data: 'fleet_name'
                            },
                            {
                                data: 'created_at',
                            },
                            {
                                data: 'actions',
                                className: 'text-end',
                            },
                        ],
                        columnDefs: [
                            {
                                targets: 2,
                                render: DataTable.render.date(DATETIME_FORMAT)
                            },
                            {
                                orderable: false,
                                targets: [3]
                            },
                        ],
                        order: [[0, 'asc']],
                        paging: false
                    });
                }

                // Initialize Bootstrap tooltips
                fleetfinderBootstrapTooltip({selector: '#table_available-fleets'});
            };

            /**
             * Fetch and update fleet data
             */
            const fetchFleetData = () => {
                fetchGet({url: '{% url "fleetfinder:ajax_dashboard" %}'})
                    .then(initializeOrUpdateTable)
                    .catch((error) => {
                        console.error('Error fetching fleet data:', error);
                    });
            };

            // Initial load
            fetchFleetData();

            // Refresh every 30 seconds
            setInterval(fetchFleetData, 30000);
        });
    </script>
{% endblock %}
