{% extends 'base.html' %}

{% block title %}{% if form.instance.pk %}Update{% else %}Create{% endif %} Appointment - Task Manager{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <h4 class="mb-0">{% if form.instance.pk %}Update{% else %}Create New{% endif %} Appointment</h4>
                </div>
                <div class="card-body">
                    <form method="post" id="appointment-form" novalidate>
                        {% csrf_token %}
                        
                        {% if form.non_field_errors %}
                            <div class="alert alert-danger">
                                <h5 class="alert-heading">Please correct the following errors:</h5>
                                <ul class="mb-0">
                                    {% for error in form.non_field_errors %}
                                        <li>{{ error }}</li>
                                    {% endfor %}
                                </ul>
                            </div>
                        {% endif %}
                        
                        {% if form.errors %}
                            <div class="alert alert-warning">
                                <h5 class="alert-heading">Please correct the errors below:</h5>
                                <ul class="mb-0">
                                    {% for field in form %}
                                        {% for error in field.errors %}
                                            <li><strong>{{ field.label }}:</strong> {{ error }}</li>
                                        {% endfor %}
                                    {% endfor %}
                                </ul>
                            </div>
                        {% endif %}
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="{{ form.service.id_for_label }}" class="form-label">
                                        {{ form.service.label }}
                                        {% if form.service.field.required %}<span class="text-danger">*</span>{% endif %}
                                    </label>
                                    {{ form.service }}
                                    {% if form.service.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ form.service.errors|join:", " }}
                                        </div>
                                    {% endif %}
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="{{ form.staff_member.id_for_label }}" class="form-label">
                                        {{ form.staff_member.label }}
                                        {% if form.staff_member.field.required %}<span class="text-danger">*</span>{% endif %}
                                    </label>
                                    {{ form.staff_member }}
                                    <small class="form-text text-muted">Leave blank for any available staff</small>
                                    {% if form.staff_member.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ form.staff_member.errors|join:", " }}
                                        </div>
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="{{ form.start_time.id_for_label }}" class="form-label">
                                        Start Time
                                        <span class="text-danger">*</span>
                                    </label>
                                    <input type="datetime-local" 
                                           id="{{ form.start_time.id_for_label }}" 
                                           name="{{ form.start_time.name }}" 
                                           class="form-control" 
                                           value="{{ form.start_time.value|default:''|date:'Y-m-d\TH:i' }}"
                                           required>
                                    {% if form.start_time.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ form.start_time.errors|join:", " }}
                                        </div>
                                    {% endif %}
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="{{ form.end_time.id_for_label }}" class="form-label">
                                        End Time
                                        <span class="text-danger">*</span>
                                    </label>
                                    <input type="datetime-local" 
                                           id="{{ form.end_time.id_for_label }}" 
                                           name="{{ form.end_time.name }}" 
                                           class="form-control" 
                                           value="{{ form.end_time.value|default:''|date:'Y-m-d\TH:i' }}"
                                           required>
                                    {% if form.end_time.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ form.end_time.errors|join:", " }}
                                        </div>
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                        
                        {% if form.status %}
                        <div class="mb-3">
                            <div class="form-group">
                                <label for="{{ form.status.id_for_label }}" class="form-label">
                                    {{ form.status.label }}
                                    {% if form.status.field.required %}<span class="text-danger">*</span>{% endif %}
                                </label>
                                {{ form.status }}
                                {% if form.status.errors %}
                                    <div class="invalid-feedback d-block">
                                        {{ form.status.errors|join:", " }}
                                    </div>
                                {% endif %}
                            </div>
                        </div>
                        {% endif %}
                        
                        <div class="mb-3">
                            <div class="form-group">
                                <label for="{{ form.notes.id_for_label }}" class="form-label">
                                    {{ form.notes.label }}
                                    {% if form.notes.field.required %}<span class="text-danger">*</span>{% endif %}
                                </label>
                                {{ form.notes }}
                                {% if form.notes.errors %}
                                    <div class="invalid-feedback d-block">
                                        {{ form.notes.errors|join:", " }}
                                    </div>
                                {% endif %}
                            </div>
                        </div>
                        
                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <a href="{% if form.instance.pk %}{% url 'appointments:appointment-detail' form.instance.pk %}{% else %}{% url 'appointments:appointment-list' %}{% endif %}" 
                               class="btn btn-outline-secondary me-md-2">
                                Cancel
                            </a>
                            <button type="submit" class="btn btn-primary">
                                {% if form.instance.pk %}Update{% else %}Create{% endif %} Appointment
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add any additional JavaScript for date/time pickers or dynamic form behavior -->
<script>
(function() {
    'use strict';
    
    document.addEventListener('DOMContentLoaded', function() {
        // Get form elements
        const serviceSelect = document.getElementById('{{ form.service.id_for_label }}');
        const startTimeInput = document.getElementById('{{ form.start_time.id_for_label }}');
        const endTimeInput = document.getElementById('{{ form.end_time.id_for_label }}');
        
        if (!serviceSelect || !startTimeInput || !endTimeInput) {
            console.error('Required form elements not found');
            return;
        }
        
        // Store service durations in a variable that will be populated by Django
        const serviceDurations = {
            {% for service in form.service.field.queryset %}
                '{{ service.id }}': {{ service.duration.total_seconds }}{% if not forloop.last %},{% endif %}
            {% endfor %}
        };
        
        // Function to update end time based on service duration
        function updateEndTime() {
            try {
                const serviceId = serviceSelect.value;
                const startTime = startTimeInput.value;
                
                if (!serviceId || !startTime) {
                    return;
                }
                
                const durationSeconds = serviceDurations[serviceId] || 3600; // Default to 1 hour if not found
                const start = new Date(startTime);
                
                if (isNaN(start.getTime())) {
                    console.error('Invalid start time');
                    return;
                }
                
                const end = new Date(start.getTime() + (durationSeconds * 1000));
                const endTimeString = end.toISOString().slice(0, 16);
                endTimeInput.value = endTimeString;
                
            } catch (error) {
                console.error('Error updating end time:', error);
            }
        }
        
        // Add event listeners
        serviceSelect.addEventListener('change', updateEndTime);
        startTimeInput.addEventListener('change', updateEndTime);
        
        // Initialize end time if both service and start time are already selected
        if (serviceSelect.value && startTimeInput.value) {
            updateEndTime();
        }
    });
})();
</script>
{% endblock %}
