<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout}">

<head>
    <title>My Activities</title>
</head>

<body>
    <div layout:fragment="content">
        <div class="row">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2>
                        <i class="bi bi-list-task text-primary"></i>
                        My Activities
                    </h2>
                    <a th:href="@{/activities/upload}" class="btn btn-primary">
                        <i class="bi bi-cloud-upload"></i> Upload Activity
                    </a>
                </div>

                <!-- Loading Indicator -->
                <div id="loadingIndicator" class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2 text-muted">Loading your activities...</p>
                </div>

                <!-- Error Alert -->
                <div id="errorAlert" class="alert alert-danger d-none" role="alert">
                    <i class="bi bi-exclamation-triangle-fill"></i>
                    <span id="errorMessage"></span>
                </div>

                <!-- Activities List -->
                <div id="activitiesList" class="d-none">
                    <!-- Will be populated by JavaScript -->
                </div>

                <!-- Empty State -->
                <div id="emptyState" class="text-center py-5 d-none">
                    <i class="bi bi-inbox" style="font-size: 4rem; color: #d1d5db;"></i>
                    <h4 class="mt-3">No Activities Yet</h4>
                    <p class="text-muted">Upload your first FIT file to get started!</p>
                    <a th:href="@{/activities/upload}" class="btn btn-primary mt-3">
                        <i class="bi bi-cloud-upload"></i> Upload Activity
                    </a>
                </div>

                <!-- Pagination -->
                <nav id="pagination" aria-label="Activities pagination" class="mt-4 d-none">
                    <ul class="pagination justify-content-center" id="paginationList">
                        <!-- Will be populated by JavaScript -->
                    </ul>
                </nav>
            </div>
        </div>

        <!-- Delete Confirmation Modal -->
        <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="deleteModalLabel">
                            <i class="bi bi-exclamation-triangle text-danger"></i>
                            Delete Activity
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <p>Are you sure you want to delete this activity?</p>
                        <p class="text-danger mb-0"><strong>This action cannot be undone.</strong></p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-danger" id="confirmDeleteBtn">
                            <i class="bi bi-trash"></i> Delete
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Custom Scripts -->
    <th:block layout:fragment="scripts">
        <script th:inline="javascript">
            document.addEventListener('DOMContentLoaded', function() {
                const loadingIndicator = document.getElementById('loadingIndicator');
                const errorAlert = document.getElementById('errorAlert');
                const errorMessage = document.getElementById('errorMessage');
                const activitiesList = document.getElementById('activitiesList');
                const emptyState = document.getElementById('emptyState');
                const pagination = document.getElementById('pagination');

                let currentPage = 0;
                let totalPages = 0;
                let activityToDelete = null;

                // Load activities
                loadActivities(currentPage);

                async function loadActivities(page) {
                    try {
                        // Show loading
                        loadingIndicator.classList.remove('d-none');
                        activitiesList.classList.add('d-none');
                        emptyState.classList.add('d-none');
                        errorAlert.classList.add('d-none');
                        pagination.classList.add('d-none');

                        const response = await FitPubAuth.authenticatedFetch(
                            `/api/activities?page=${page}&size=10&sort=startedAt,desc`
                        );

                        if (response.ok) {
                            const data = await response.json();

                            // Hide loading
                            loadingIndicator.classList.add('d-none');

                            if (data.content && data.content.length > 0) {
                                renderActivities(data.content);
                                renderPagination(data);
                                activitiesList.classList.remove('d-none');
                                pagination.classList.remove('d-none');
                            } else {
                                emptyState.classList.remove('d-none');
                            }

                            totalPages = data.totalPages;
                            currentPage = data.number;
                        } else {
                            throw new Error('Failed to load activities');
                        }
                    } catch (error) {
                        console.error('Error loading activities:', error);
                        loadingIndicator.classList.add('d-none');
                        errorMessage.textContent = 'Failed to load activities. Please try again.';
                        errorAlert.classList.remove('d-none');
                    }
                }

                function renderActivities(activities) {
                    activitiesList.innerHTML = activities.map(activity => `
                        <div class="card activity-card mb-3">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-8">
                                        <h5 class="card-title">
                                            <a href="/activities/${activity.id}" class="text-decoration-none">
                                                ${escapeHtml(activity.title || 'Untitled Activity')}
                                            </a>
                                        </h5>
                                        <p class="text-muted mb-2">
                                            <span class="activity-type-badge activity-type-${activity.activityType.toLowerCase()}">
                                                ${activity.activityType}
                                            </span>
                                            <span class="ms-2">
                                                <i class="bi bi-calendar"></i>
                                                ${new Date(activity.startedAt).toLocaleDateString()}
                                            </span>
                                            <span class="ms-2 visibility-${activity.visibility.toLowerCase()}">
                                                <i class="bi bi-${getVisibilityIcon(activity.visibility)}"></i>
                                                ${activity.visibility}
                                            </span>
                                        </p>
                                        ${activity.description ? `<p class="card-text">${escapeHtml(activity.description).substring(0, 150)}${activity.description.length > 150 ? '...' : ''}</p>` : ''}
                                    </div>
                                    <div class="col-md-4">
                                        <small class="text-muted">
                                            <strong>Distance:</strong> ${formatDistance(activity.totalDistance)}<br>
                                            <strong>Duration:</strong> ${formatDuration(activity.totalDuration)}<br>
                                            <strong>Elevation:</strong> ${activity.elevationGain ? Math.round(activity.elevationGain) + 'm' : 'N/A'}
                                        </small>
                                    </div>
                                </div>
                                <div class="mt-3 d-flex gap-2">
                                    <a href="/activities/${activity.id}" class="btn btn-sm btn-outline-primary">
                                        <i class="bi bi-eye"></i> View
                                    </a>
                                    <a href="/activities/${activity.id}/edit" class="btn btn-sm btn-outline-secondary">
                                        <i class="bi bi-pencil"></i> Edit
                                    </a>
                                    <button class="btn btn-sm btn-outline-danger" onclick="confirmDelete('${activity.id}')">
                                        <i class="bi bi-trash"></i> Delete
                                    </button>
                                </div>
                            </div>
                        </div>
                    `).join('');
                }

                function renderPagination(data) {
                    const paginationList = document.getElementById('paginationList');
                    let html = '';

                    // Previous button
                    html += `
                        <li class="page-item ${data.first ? 'disabled' : ''}">
                            <a class="page-link" href="#" onclick="changePage(${data.number - 1}); return false;">
                                <i class="bi bi-chevron-left"></i>
                            </a>
                        </li>
                    `;

                    // Page numbers
                    const startPage = Math.max(0, data.number - 2);
                    const endPage = Math.min(data.totalPages - 1, data.number + 2);

                    if (startPage > 0) {
                        html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
                    }

                    for (let i = startPage; i <= endPage; i++) {
                        html += `
                            <li class="page-item ${i === data.number ? 'active' : ''}">
                                <a class="page-link" href="#" onclick="changePage(${i}); return false;">${i + 1}</a>
                            </li>
                        `;
                    }

                    if (endPage < data.totalPages - 1) {
                        html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
                    }

                    // Next button
                    html += `
                        <li class="page-item ${data.last ? 'disabled' : ''}">
                            <a class="page-link" href="#" onclick="changePage(${data.number + 1}); return false;">
                                <i class="bi bi-chevron-right"></i>
                            </a>
                        </li>
                    `;

                    paginationList.innerHTML = html;
                }

                // Global functions for pagination and delete
                window.changePage = function(page) {
                    loadActivities(page);
                    window.scrollTo({ top: 0, behavior: 'smooth' });
                };

                window.confirmDelete = function(activityId) {
                    activityToDelete = activityId;
                    const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
                    modal.show();
                };

                // Delete confirmation
                document.getElementById('confirmDeleteBtn').addEventListener('click', async function() {
                    if (!activityToDelete) return;

                    try {
                        const response = await FitPubAuth.authenticatedFetch(
                            `/api/activities/${activityToDelete}`,
                            { method: 'DELETE' }
                        );

                        if (response.ok) {
                            // Close modal
                            const modal = bootstrap.Modal.getInstance(document.getElementById('deleteModal'));
                            modal.hide();

                            // Reload activities
                            loadActivities(currentPage);

                            // Show success message
                            FitPub.showAlert('Activity deleted successfully', 'success');
                        } else {
                            throw new Error('Failed to delete activity');
                        }
                    } catch (error) {
                        console.error('Delete error:', error);
                        FitPub.showAlert('Failed to delete activity. Please try again.', 'danger');
                    }

                    activityToDelete = null;
                });

                // Helper functions
                function formatDistance(meters) {
                    if (!meters) return 'N/A';
                    if (meters >= 1000) {
                        return (meters / 1000).toFixed(1) + ' km';
                    }
                    return Math.round(meters) + ' m';
                }

                function formatDuration(seconds) {
                    if (!seconds) return 'N/A';
                    const hours = Math.floor(seconds / 3600);
                    const minutes = Math.floor((seconds % 3600) / 60);

                    if (hours > 0) {
                        return hours + 'h ' + minutes + 'm';
                    }
                    return minutes + 'm';
                }

                function getVisibilityIcon(visibility) {
                    switch (visibility) {
                        case 'PUBLIC': return 'globe';
                        case 'FOLLOWERS': return 'people';
                        case 'PRIVATE': return 'lock';
                        default: return 'question-circle';
                    }
                }

                function escapeHtml(text) {
                    const div = document.createElement('div');
                    div.textContent = text;
                    return div.innerHTML;
                }
            });
        </script>
    </th:block>
</body>
</html>
