{% extends "layout.html" %}

{% block content %}
<div class="page-container">
    <h1>Time Tracking</h1>

    <div class="timer-section">
        {% if active_entry %}
            <div class="active-timer">
                <h2>Currently Working</h2>
                <p>Started at: {{ active_entry.arrival_time|format_datetime }}</p>
                <div id="timer" data-start="{{ active_entry.arrival_time.timestamp() }}">00:00:00</div>
                <button id="leave-btn" class="leave-btn" data-id="{{ active_entry.id }}">Leave</button>
            </div>
        {% else %}
            <div class="inactive-timer">
                <h2>Not Currently Working</h2>
                <button id="arrive-btn" class="arrive-btn">Arrive</button>
            </div>
        {% endif %}
    </div>

    <div class="history-section">
        <h2>Time Entry History</h2>
        <!-- Time history table -->
        <table class="time-history">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Arrival</th>
                    <th>Departure</th>
                    <th>Duration</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="time-history-body">
                {% for entry in history %}
                <tr data-entry-id="{{ entry.id }}" data-iso-date="{{ entry.arrival_time.strftime('%Y-%m-%d') }}">
                    <td>{{ entry.arrival_time|format_date }}</td>
                    <td>{{ entry.arrival_time|format_time }}</td>
                    <td>{{ entry.departure_time|format_time if entry.departure_time else 'Active' }}</td>
                    <td>{{ entry.duration|format_duration if entry.duration else 'N/A' }}</td>
                    <td>
                        <button class="edit-entry-btn" data-id="{{ entry.id }}">Edit</button>
                        <button class="delete-entry-btn" data-id="{{ entry.id }}">Delete</button>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>

        <!-- Edit Entry Modal -->
        <div id="edit-modal" class="modal">
            <div class="modal-content">
                <span class="close">&times;</span>
                <h3>Edit Time Entry</h3>
                <form id="edit-entry-form">
                    <input type="hidden" id="edit-entry-id">
                    <div class="form-group">
                        <label for="edit-arrival-date">Arrival Date:</label>
                        <input type="date" id="edit-arrival-date" required>
                    </div>
                    <div class="form-group">
                        <label for="edit-arrival-time">Arrival Time:</label>
                        <input type="time" id="edit-arrival-time" required>
                    </div>
                    <div class="form-group">
                        <label for="edit-departure-date">Departure Date:</label>
                        <input type="date" id="edit-departure-date">
                    </div>
                    <div class="form-group">
                        <label for="edit-departure-time">Departure Time:</label>
                        <input type="time" id="edit-departure-time">
                    </div>
                    <button type="submit" class="btn">Save Changes</button>
                </form>
            </div>
        </div>

        <!-- Delete Confirmation Modal -->
        <div id="delete-modal" class="modal">
            <div class="modal-content">
                <span class="close">&times;</span>
                <h3>Confirm Deletion</h3>
                <p>Are you sure you want to delete this time entry? This action cannot be undone.</p>
                <input type="hidden" id="delete-entry-id">
                <div class="modal-actions">
                    <button id="confirm-delete" class="btn btn-danger">Delete</button>
                    <button id="cancel-delete" class="btn">Cancel</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Edit entry functionality
        document.querySelectorAll('.edit-entry-btn').forEach(button => {
            button.addEventListener('click', function() {
                const entryId = this.getAttribute('data-id');
                const row = document.querySelector(`tr[data-entry-id="${entryId}"]`);
                const cells = row.querySelectorAll('td');

                // Get date and time from the row
                const dateStr = cells[0].textContent;
                const arrivalTimeStr = cells[1].textContent;
                const departureTimeStr = cells[2].textContent !== 'Active' ? cells[2].textContent : '';

                // For edit form, we need ISO format (YYYY-MM-DD)
                // Parse the displayed date back to ISO format
                const entryRow = document.querySelector(`tr[data-entry-id="${entryId}"]`);
                const isoDate = entryRow.dataset.isoDate || dateStr;

                // Set values in the form
                document.getElementById('edit-entry-id').value = entryId;
                document.getElementById('edit-arrival-date').value = isoDate;
                document.getElementById('edit-arrival-time').value = arrivalTimeStr;

                if (departureTimeStr) {
                    document.getElementById('edit-departure-date').value = isoDate;
                    document.getElementById('edit-departure-time').value = departureTimeStr;
                } else {
                    document.getElementById('edit-departure-date').value = '';
                    document.getElementById('edit-departure-time').value = '';
                }

                // Show the modal
                document.getElementById('edit-modal').style.display = 'block';
            });
        });

        // Delete entry functionality
        document.querySelectorAll('.delete-entry-btn').forEach(button => {
            button.addEventListener('click', function() {
                const entryId = this.getAttribute('data-id');
                document.getElementById('delete-entry-id').value = entryId;
                document.getElementById('delete-modal').style.display = 'block';
            });
        });

        // Close modals when clicking the X
        document.querySelectorAll('.close').forEach(closeBtn => {
            closeBtn.addEventListener('click', function() {
                this.closest('.modal').style.display = 'none';
            });
        });

        // Close modals when clicking outside
        window.addEventListener('click', function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        });

        // Cancel delete
        document.getElementById('cancel-delete').addEventListener('click', function() {
            document.getElementById('delete-modal').style.display = 'none';
        });

        // Confirm delete
        document.getElementById('confirm-delete').addEventListener('click', function() {
            const entryId = document.getElementById('delete-entry-id').value;

            fetch(`/api/delete/${entryId}`, {
                method: 'DELETE',
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Remove the row from the table
                    document.querySelector(`tr[data-entry-id="${entryId}"]`).remove();
                    // Close the modal
                    document.getElementById('delete-modal').style.display = 'none';
                    // Show success message
                    alert('Entry deleted successfully');
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred while deleting the entry');
            });
        });

        // Submit edit form
        document.getElementById('edit-entry-form').addEventListener('submit', function(e) {
            e.preventDefault();

            const entryId = document.getElementById('edit-entry-id').value;
            const arrivalDate = document.getElementById('edit-arrival-date').value;
            const arrivalTime = document.getElementById('edit-arrival-time').value;
            const departureDate = document.getElementById('edit-departure-date').value;
            const departureTime = document.getElementById('edit-departure-time').value;

            // Format datetime strings as ISO 8601
            const arrivalDateTime = `${arrivalDate}T${arrivalTime}:00`;
            let departureDateTime = null;

            if (departureDate && departureTime) {
                departureDateTime = `${departureDate}T${departureTime}:00`;
            }

            // Send update request
            fetch(`/api/update/${entryId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    arrival_time: arrivalDateTime,
                    departure_time: departureDateTime
                }),
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Close the modal
                    document.getElementById('edit-modal').style.display = 'none';
                    // Refresh the page to show updated data
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred while updating the entry');
            });
        });
    });
</script>
{% endblock %}