{% extends "base.html" %}

{% block title %}Edit Template - {{ config.APP_NAME }}{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8 max-w-2xl">
    <!-- Header -->
    <div class="mb-6">
        <a href="{{ url_for('time_entry_templates.list_templates') }}" 
           class="text-blue-600 hover:text-blue-800 dark:text-blue-400 mb-4 inline-block">
            <i class="fas fa-arrow-left mr-2"></i> Back to Templates
        </a>
        <h1 class="text-3xl font-bold text-gray-900 dark:text-white">{{ _('Edit Template') }}</h1>
        <p class="text-gray-600 dark:text-gray-400 mt-2">Modify your time entry template</p>
    </div>

    <!-- Form -->
    <div class="bg-card-light dark:bg-card-dark rounded-lg shadow-md p-6">
        <form method="POST" action="{{ url_for('time_entry_templates.edit_template', template_id=template.id) }}">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            
            <!-- Template Name -->
            <div class="mb-6">
                <label for="name" class="form-label">
                    Template Name <span class="text-red-500">*</span>
                </label>
                <input type="text" 
                       id="name" 
                       name="name" 
                       value="{{ template.name }}"
                       required 
                       class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                       placeholder="{{ _('e.g., Daily Standup, Client Meeting') }}">
            </div>

            <!-- Project -->
            <div class="mb-6">
                <label for="project_id" class="form-label">
                    Project
                </label>
                <select id="project_id" 
                        name="project_id" 
                        onchange="loadProjectTasks(this.value)"
                        class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white">
                    <option value="">Select a project (optional)</option>
                    {% for project in projects %}
                    <option value="{{ project.id }}" 
                            {% if template.project_id == project.id %}selected{% endif %}>
                        {{ project.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>

            <!-- Task -->
            <div class="mb-6">
                <label for="task_id" class="form-label">
                    Task
                </label>
                <select id="task_id" 
                        name="task_id" 
                        data-selected="{{ template.task_id if template.task_id else '' }}"
                        class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white">
                    <option value="">Select a task (optional)</option>
                    {% if template.task %}
                    <option value="{{ template.task.id }}" selected>{{ template.task.name }}</option>
                    {% endif %}
                </select>
                <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                    Select a project first to load tasks
                </p>
            </div>

            <!-- Default Duration -->
            <div class="mb-6">
                <label for="default_duration" class="form-label">
                    Default Duration (hours)
                </label>
                <input type="number" 
                       id="default_duration" 
                       name="default_duration" 
                       value="{{ template.default_duration if template.default_duration else '' }}"
                       step="0.25" 
                       min="0"
                       class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                       placeholder="{{ _('e.g., 1.0, 0.5') }}">
                <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                    Leave empty for manual timer start/stop
                </p>
            </div>

            <!-- Default Notes -->
            <div class="mb-6">
                <label for="default_notes" class="form-label">
                    Default Notes
                </label>
                <textarea id="default_notes" 
                          name="default_notes" 
                          rows="3"
                          class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                          placeholder="{{ _('Pre-fill notes for this type of time entry') }}">{{ template.default_notes if template.default_notes else '' }}</textarea>
            </div>

            <!-- Tags -->
            <div class="mb-6">
                <label for="tags" class="form-label">
                    Tags
                </label>
                <input type="text" 
                       id="tags" 
                       name="tags" 
                       value="{{ template.tags if template.tags else '' }}"
                       class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                       placeholder="{{ _('e.g., meeting, development, admin') }}">
                <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                    Comma-separated tags
                </p>
            </div>

            <!-- Actions -->
            <div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
                <a href="{{ url_for('time_entry_templates.list_templates') }}" 
                   class="btn btn-secondary text-center">
                    Cancel
                </a>
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save mr-2"></i> Save Changes
                </button>
            </div>
        </form>
    </div>

    <!-- Template Stats -->
    <div class="mt-6 bg-blue-50 dark:bg-blue-900/20 rounded-lg p-4">
        <div class="flex items-center text-sm text-blue-800 dark:text-blue-200">
            <i class="fas fa-chart-line mr-3"></i>
            <span>
                This template has been used <strong>{{ template.usage_count }}</strong> time{{ 's' if template.usage_count != 1 else '' }}
                {% if template.last_used_at %}
                (last used {{ template.last_used_at|timeago }})
                {% endif %}
            </span>
        </div>
    </div>
</div>

<script>
const tasksApiUrlTemplate = {{ url_for('api.get_project_tasks', project_id=0)|tojson }};
function buildTasksUrl(projectId) {
    const pid = String(projectId || '').trim();
    if (!pid) return tasksApiUrlTemplate;
    return String(tasksApiUrlTemplate).replace(/\/0\/tasks$/, '/' + encodeURIComponent(pid) + '/tasks');
}
function loadProjectTasks(projectId) {
    const taskSelect = document.getElementById('task_id');
    const selectedTaskId = taskSelect.dataset.selected;
    
    // Clear existing options except the currently selected one
    taskSelect.innerHTML = '<option value="">Select a task (optional)</option>';
    
    if (!projectId) {
        return;
    }
    
    // Fetch tasks for the selected project
    fetch(buildTasksUrl(projectId))
        .then(response => response.json())
        .then(data => {
            data.tasks.forEach(task => {
                const option = document.createElement('option');
                option.value = task.id;
                option.textContent = task.name;
                if (task.id == selectedTaskId) {
                    option.selected = true;
                }
                taskSelect.appendChild(option);
            });
        })
        .catch(error => {
            console.error('Error loading tasks:', error);
        });
}

// Load tasks if project is pre-selected
document.addEventListener('DOMContentLoaded', function() {
    const projectSelect = document.getElementById('project_id');
    if (projectSelect.value) {
        loadProjectTasks(projectSelect.value);
    }
});
</script>
{% endblock %}

