{% extends "shared/frontend/base.html" %}

{% block title %}Rediger Sag - BMC Hub{% endblock %}

{% block extra_css %}
<style>
    .form-container {
        max-width: 600px;
        margin: 2rem auto;
    }

    .form-container h1 {
        margin-bottom: 2rem;
    }

    .card {
        border: none;
        border-radius: 12px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        border: 1px solid rgba(0,0,0,0.1);
    }

    .card-body {
        padding: 2rem;
    }

    .form-group {
        margin-bottom: 1.5rem;
    }

    .form-group label {
        font-weight: 600;
        color: var(--accent);
        margin-bottom: 0.5rem;
        display: block;
    }

    .form-control, .form-select {
        border-radius: 8px;
        border: 1px solid rgba(0,0,0,0.1);
    }

    .btn-submit {
        background-color: var(--accent);
        color: white;
        padding: 0.7rem 2rem;
        border: none;
        border-radius: 8px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s;
    }

    .btn-submit:hover {
        background-color: #0056b3;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(15, 76, 117, 0.3);
    }

    .btn-cancel {
        background-color: #6c757d;
        color: white;
        padding: 0.7rem 2rem;
        border: none;
        border-radius: 8px;
        font-weight: 600;
        cursor: pointer;
        text-decoration: none;
        display: inline-block;
        transition: all 0.2s;
    }

    .btn-cancel:hover {
        background-color: #5a6268;
    }

    .button-group {
        display: flex;
        gap: 1rem;
        margin-top: 2rem;
    }

    .error {
        display: none;
        padding: 1rem;
        background-color: #f8d7da;
        border: 1px solid #f5c6cb;
        border-radius: 8px;
        color: #721c24;
        margin-bottom: 1rem;
    }

    [data-bs-theme="dark"] .error {
        background-color: #5c2b2f;
        border-color: #8c3b3f;
        color: #f8a5ac;
    }

    .success {
        display: none;
        padding: 1rem;
        background-color: #d4edda;
        border: 1px solid #c3e6cb;
        border-radius: 8px;
        color: #155724;
        margin-bottom: 1rem;
    }

    .search-results {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        background: var(--bg-body);
        border: 1px solid rgba(0,0,0,0.1);
        border-radius: 8px;
        max-height: 300px;
        overflow-y: auto;
        z-index: 1000;
        margin-top: 0.5rem;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    .search-result-item {
        padding: 0.8rem 1rem;
        cursor: pointer;
        border-bottom: 1px solid rgba(0,0,0,0.05);
        transition: background 0.2s;
    }

    .search-result-item:hover {
        background: var(--accent-light);
    }

    .search-result-item:last-child {
        border-bottom: none;
    }

    .search-result-name {
        font-weight: 600;
        color: var(--accent);
    }

    .search-result-meta {
        font-size: 0.85rem;
        color: var(--text-secondary);
    }

    .selected-item {
        display: inline-block;
        background: var(--accent-light);
        color: var(--accent);
        padding: 0.4rem 0.8rem;
        border-radius: 20px;
        font-size: 0.85rem;
        font-weight: 500;
        margin-right: 0.5rem;
        margin-bottom: 0.5rem;
    }

    .selected-item button {
        background: none;
        border: none;
        color: var(--accent);
        cursor: pointer;
        margin-left: 0.4rem;
        font-weight: bold;
    }
</style>
{% endblock %}

{% block content %}
<div class="form-container">
    <div class="card">
        <div class="card-body">
            <h1 style="color: var(--accent); margin-bottom: 2rem;">✏️ Rediger Sag</h1>
            
            <div id="error" class="error"></div>
            <div id="success" class="success"></div>
            
            <form id="editForm">
                <div class="form-group">
                    <label for="titel">Titel *</label>
                    <input type="text" class="form-control" id="titel" placeholder="Indtast sagens titel" required value="{{ case.titel }}">
                </div>
                
                <div class="form-group">
                    <label for="beskrivelse">Beskrivelse</label>
                    <textarea class="form-control" id="beskrivelse" rows="4" placeholder="Optionalt: Detaljeret beskrivelse af sagen">{{ case.beskrivelse or '' }}</textarea>
                </div>
                
                <div class="form-group">
                    <label for="type">Type *</label>
                    <select class="form-select" id="type" required>
                        <option value="ticket" {% if (case.template_key or case.type) == 'ticket' %}selected{% endif %}>🎫 Ticket</option>
                        <option value="pipeline" {% if (case.template_key or case.type) == 'pipeline' %}selected{% endif %}>📈 Pipeline</option>
                        <option value="opgave" {% if (case.template_key or case.type) == 'opgave' %}selected{% endif %}>🧩 Opgave</option>
                        <option value="ordre" {% if (case.template_key or case.type) == 'ordre' %}selected{% endif %}>🧾 Ordre</option>
                        <option value="projekt" {% if (case.template_key or case.type) == 'projekt' %}selected{% endif %}>📁 Projekt</option>
                        <option value="service" {% if (case.template_key or case.type) == 'service' %}selected{% endif %}>🛠️ Service</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="status">Status *</label>
                    <select class="form-select" id="status" required>
                        <option value="">Vælg status</option>
                        <option value="åben" {% if case.status == 'åben' %}selected{% endif %}>Åben</option>
                        <option value="afventer" {% if case.status == 'afventer' %}selected{% endif %}>Afventer</option>
                        <option value="lukket" {% if case.status == 'lukket' %}selected{% endif %}>Lukket</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="ansvarlig_bruger_id">Ansvarlig medarbejder</label>
                    <select class="form-select" id="ansvarlig_bruger_id">
                        <option value="">Ingen</option>
                        {% for user in assignment_users or [] %}
                        <option value="{{ user.user_id }}" {% if case.ansvarlig_bruger_id == user.user_id %}selected{% endif %}>{{ user.display_name }}</option>
                        {% endfor %}
                    </select>
                </div>

                <div class="form-group">
                    <label for="assigned_group_id">Ansvarlig gruppe</label>
                    <select class="form-select" id="assigned_group_id">
                        <option value="">Ingen</option>
                        {% for group in assignment_groups or [] %}
                        <option value="{{ group.id }}" {% if case.assigned_group_id == group.id %}selected{% endif %}>{{ group.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="deadline">Deadline (valgfrit)</label>
                    <input type="datetime-local" class="form-control" id="deadline" value="{{ case.deadline.strftime('%Y-%m-%dT%H:%M') if case.deadline else '' }}">
                </div>
                
                <div class="button-group">
                    <button type="submit" class="btn-submit">Gem Ændringer</button>
                    <a href="/sag/{{ case.id }}/v3" class="btn-cancel">Annuller</a>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    const caseId = {{ case.id }};
    const currentType = "{{ case.template_key or case.type or 'ticket' }}";

    async function loadCaseTypesSelect() {
        const select = document.getElementById('type');
        if (!select) return;
        try {
            const res = await fetch('/api/v1/settings/case_types');
            if (!res.ok) return;
            const setting = await res.json();
            const types = JSON.parse(setting.value || '[]');
            if (!Array.isArray(types) || types.length === 0) return;

            const typeSet = new Set(types);
            if (currentType) {
                typeSet.add(currentType);
            }

            select.innerHTML = Array.from(typeSet)
                .map((type) => `<option value="${type}" ${type === currentType ? 'selected' : ''}>${type}</option>`)
                .join('');
        } catch (err) {
            console.error('Failed to load case types', err);
        }
    }

    document.addEventListener('DOMContentLoaded', loadCaseTypesSelect);

    document.getElementById('editForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const titel = document.getElementById('titel').value;
        const type = document.getElementById('type').value;
        const status = document.getElementById('status').value;
        
        if (!titel || !type || !status) {
            document.getElementById('error').textContent = `❌ Udfyld alle påkrævede felter`;
            document.getElementById('error').style.display = 'block';
            return;
        }
        
        const data = {
            titel: titel,
            beskrivelse: document.getElementById('beskrivelse').value || '',
            type: type,
            status: status,
            ansvarlig_bruger_id: document.getElementById('ansvarlig_bruger_id').value ? parseInt(document.getElementById('ansvarlig_bruger_id').value) : null,
            assigned_group_id: document.getElementById('assigned_group_id').value ? parseInt(document.getElementById('assigned_group_id').value) : null,
            deadline: document.getElementById('deadline').value || null
        };
        
        console.log('Updating case with data:', data);
        
        try {
            const response = await fetch(`/api/v1/sag/${caseId}`, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });
            
            console.log('Response status:', response.status);
            
            if (response.ok) {
                const result = await response.json();
                console.log('Updated case:', result);
                
                document.getElementById('success').textContent = `✅ Sag opdateret! Omdirigerer...`;
                document.getElementById('success').style.display = 'block';
                setTimeout(() => {
                    window.location.href = `/sag/${caseId}/v3`;
                }, 1000);
            } else {
                const errorText = await response.text();
                console.error('Error response:', errorText);
                try {
                    const error = JSON.parse(errorText);
                    document.getElementById('error').textContent = `❌ Fejl: ${error.detail || errorText}`;
                } catch {
                    document.getElementById('error').textContent = `❌ Fejl: ${errorText}`;
                }
                document.getElementById('error').style.display = 'block';
            }
        } catch (err) {
            console.error('Exception:', err);
            document.getElementById('error').textContent = `❌ Fejl: ${err.message}`;
            document.getElementById('error').style.display = 'block';
        }
    });
</script>
{% endblock %}
