{% extends 'admin/base.html' %}

{% block title %}Support Ticket - {{ ticket[1] }}{% endblock %}

{% block content %}
<div class="page-header">
    <div>
        <h1 class="page-title">{{ ticket[1] }}</h1>
        <p class="page-subtitle">Ticket #{{ ticket[0][:8] }} from {{ ticket[7] }}</p>
    </div>
    <a href="{{ url_for('admin.support_tickets') }}" class="btn btn-secondary">
        <i class="fa-light fa-arrow-left"></i> Back to Tickets
    </a>
</div>

<div class="card" style="margin-bottom: 24px;">
    <div class="card-body">
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 20px;">
            <div>
                <div style="font-size: 12px; text-transform: uppercase; color: #94a3b8; letter-spacing: 0.08em; font-weight: 600; margin-bottom: 6px;">Priority</div>
                <span class="status status-{{ ticket[3] }}">{{ ticket[3]|title }}</span>
            </div>
            <div>
                <div style="font-size: 12px; text-transform: uppercase; color: #94a3b8; letter-spacing: 0.08em; font-weight: 600; margin-bottom: 6px;">Status</div>
                <select id="statusSelect" class="form-select" style="display: inline-block; width: auto; padding: 4px 12px; border-radius: 999px; font-size: 12px; font-weight: 600;">
                    <option value="open" {% if ticket[4] == 'open' %}selected{% endif %}>Open</option>
                    <option value="in_progress" {% if ticket[4] == 'in_progress' %}selected{% endif %}>In Progress</option>
                    <option value="resolved" {% if ticket[4] == 'resolved' %}selected{% endif %}>Resolved</option>
                    <option value="closed" {% if ticket[4] == 'closed' %}selected{% endif %}>Closed</option>
                </select>
            </div>
            <div>
                <div style="font-size: 12px; text-transform: uppercase; color: #94a3b8; letter-spacing: 0.08em; font-weight: 600; margin-bottom: 6px;">Created</div>
                <div style="font-size: 16px; font-weight: 600; color: #0f172a;">{{ ticket[5].strftime('%B %d, %Y %I:%M %p') if ticket[5] else '—' }}</div>
            </div>
            <div>
                <div style="font-size: 12px; text-transform: uppercase; color: #94a3b8; letter-spacing: 0.08em; font-weight: 600; margin-bottom: 6px;">Last Updated</div>
                <div style="font-size: 16px; font-weight: 600; color: #0f172a;">{{ ticket[6].strftime('%B %d, %Y %I:%M %p') if ticket[6] else '—' }}</div>
            </div>
        </div>
        <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid rgba(148, 163, 184, 0.12);">
            <div style="font-size: 12px; text-transform: uppercase; color: #94a3b8; letter-spacing: 0.08em; font-weight: 600; margin-bottom: 8px;">Description</div>
            <div style="font-size: 15px; color: #475569; line-height: 1.6; white-space: pre-wrap;">{{ ticket[2] }}</div>
        </div>
        <div style="margin-top: 16px; padding-top: 16px; border-top: 1px solid rgba(148, 163, 184, 0.12);">
            <div style="font-size: 12px; text-transform: uppercase; color: #94a3b8; letter-spacing: 0.08em; font-weight: 600; margin-bottom: 8px;">Company Information</div>
            <div style="font-size: 15px; color: #475569;">
                <strong>{{ ticket[7] }}</strong><br>
                <span style="color: #94a3b8;">{{ ticket[8] }}</span>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-body" style="padding: 0;">
        <div style="padding: 20px 24px; border-bottom: 1px solid rgba(148, 163, 184, 0.12); background: #f8fafc;">
            <h3 style="margin: 0; font-size: 18px; font-weight: 600; color: #0f172a;">Conversation</h3>
        </div>
        <div id="chatMessages" style="flex: 1; overflow-y: auto; padding: 24px; display: flex; flex-direction: column; gap: 16px; max-height: 500px; min-height: 400px;">
            {% if messages %}
                {% for message in messages %}
                <div class="message {{ message[1] }}" style="display: flex; gap: 12px; max-width: 75%; {% if message[1] == 'admin' %}align-self: flex-start;{% else %}align-self: flex-end; flex-direction: row-reverse;{% endif %}">
                    <div class="message-avatar" style="width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; font-size: 14px; flex-shrink: 0; {% if message[1] == 'admin' %}background: #10b981; color: #ffffff;{% else %}background: #2563eb; color: #ffffff;{% endif %}">
                        {% if message[1] == 'admin' %}
                            A
                        {% else %}
                            {{ ticket[7][0]|upper }}
                        {% endif %}
                    </div>
                    <div class="message-content" style="display: flex; flex-direction: column; gap: 4px; {% if message[1] == 'admin' %}align-items: flex-start;{% else %}align-items: flex-end;{% endif %}">
                        <div class="message-sender" style="font-size: 12px; font-weight: 600; color: #64748b; margin-bottom: 4px;">
                            {% if message[1] == 'admin' %}
                                {{ admin_name }}
                            {% else %}
                                {{ ticket[7] }}
                            {% endif %}
                        </div>
                        <div class="message-bubble" style="padding: 12px 16px; border-radius: 16px; font-size: 14px; line-height: 1.5; word-wrap: break-word; {% if message[1] == 'admin' %}background: #f1f5f9; color: #0f172a; border-bottom-left-radius: 4px;{% else %}background: #2563eb; color: #ffffff; border-bottom-right-radius: 4px;{% endif %}">
                            {{ message[3] }}
                        </div>
                        <div class="message-time" style="font-size: 11px; color: #94a3b8; padding: 0 4px;">
                            {{ message[4].strftime('%I:%M %p') if message[4] else '' }}
                        </div>
                    </div>
                </div>
                {% endfor %}
            {% else %}
                <div style="flex: 1; display: flex; align-items: center; justify-content: center; color: #94a3b8; font-size: 14px;">
                    <p>No messages yet. Start the conversation below.</p>
                </div>
            {% endif %}
        </div>
        <div style="padding: 20px 24px; border-top: 1px solid rgba(148, 163, 184, 0.12); background: #f8fafc;">
            {% if ticket[4] == 'closed' %}
            <div style="padding: 12px 16px; background: #fef2f2; border: 1px solid #fecaca; border-radius: 12px; color: #991b1b; font-size: 14px; text-align: center;">
                <i class="fa-light fa-lock"></i> This ticket is closed. No further messages can be sent.
            </div>
            {% else %}
            <form id="messageForm" style="display: flex; gap: 12px; align-items: flex-end;">
                <textarea 
                    id="messageInput" 
                    style="flex: 1; padding: 12px 16px; border: 1px solid #dbe3ee; border-radius: 12px; font-size: 14px; color: #0f172a; font-family: inherit; resize: none; min-height: 44px; max-height: 120px;"
                    placeholder="Type your message..."
                    rows="1"
                    required></textarea>
                <button type="submit" class="btn btn-primary" id="sendButton" style="padding: 12px 24px;">
                    <i class="fa-light fa-paper-plane"></i> Send
                </button>
            </form>
            {% endif %}
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    const chatMessages = document.getElementById('chatMessages');
    const messageForm = document.getElementById('messageForm');
    const messageInput = document.getElementById('messageInput');
    const sendButton = document.getElementById('sendButton');
    const statusSelect = document.getElementById('statusSelect');
    const ticketId = '{{ ticket[0] }}';
    const adminName = '{{ admin_name }}';
    const companyName = '{{ ticket[7] }}';
    const ticketStatus = '{{ ticket[4] }}';

    // Scroll to bottom on load
    chatMessages.scrollTop = chatMessages.scrollHeight;

    // Auto-resize textarea (only if form exists)
    if (messageInput) {
        messageInput.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = Math.min(this.scrollHeight, 120) + 'px';
        });
    }

    // Status update
    statusSelect.addEventListener('change', async function() {
        const status = this.value;
        const originalValue = this.value;

        try {
            const response = await fetch(`/admin/support-tickets/${ticketId}/status`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ status: status })
            });

            const data = await response.json();

            if (!data.success) {
                alert(data.error || 'Failed to update status');
                this.value = originalValue;
            } else {
                // Reload page to update UI (show/hide message form)
                if (status === 'closed' || originalValue === 'closed') {
                    window.location.reload();
                }
            }
        } catch (error) {
            console.error('Error:', error);
            alert('An error occurred while updating status');
            this.value = originalValue;
        }
    });

    // Send message (only if ticket is not closed)
    if (messageForm && ticketStatus !== 'closed') {
        messageForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const message = messageInput.value.trim();
        if (!message) return;

        // Disable form
        sendButton.disabled = true;
        const originalButtonText = sendButton.innerHTML;
        sendButton.innerHTML = '<i class="fa-light fa-spinner fa-spin"></i> Sending...';

        try {
            const response = await fetch(`/admin/support-tickets/${ticketId}/message`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ message: message })
            });

            const data = await response.json();

            if (data.success) {
                // Add message to chat
                addMessageToChat(message, 'admin', adminName);
                messageInput.value = '';
                messageInput.style.height = 'auto';
                
                // Scroll to bottom
                setTimeout(() => {
                    chatMessages.scrollTop = chatMessages.scrollHeight;
                }, 100);
            } else {
                alert(data.error || 'Failed to send message');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('An error occurred while sending the message');
        } finally {
            sendButton.disabled = false;
            sendButton.innerHTML = originalButtonText;
        }
        });
    }

    function addMessageToChat(messageText, senderType, senderName) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${senderType}`;
        messageDiv.style.cssText = `display: flex; gap: 12px; max-width: 75%; ${senderType === 'admin' ? 'align-self: flex-start;' : 'align-self: flex-end; flex-direction: row-reverse;'}`;
        
        const now = new Date();
        const timeString = now.toLocaleTimeString('en-US', { 
            hour: '2-digit', 
            minute: '2-digit',
            hour12: true 
        });

        messageDiv.innerHTML = `
            <div class="message-avatar" style="width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; font-size: 14px; flex-shrink: 0; ${senderType === 'admin' ? 'background: #10b981; color: #ffffff;' : 'background: #2563eb; color: #ffffff;'}">
                ${senderType === 'admin' ? 'A' : companyName[0].toUpperCase()}
            </div>
            <div class="message-content" style="display: flex; flex-direction: column; gap: 4px; ${senderType === 'admin' ? 'align-items: flex-start;' : 'align-items: flex-end;'}">
                <div class="message-sender" style="font-size: 12px; font-weight: 600; color: #64748b; margin-bottom: 4px;">${senderName}</div>
                <div class="message-bubble" style="padding: 12px 16px; border-radius: 16px; font-size: 14px; line-height: 1.5; word-wrap: break-word;  ${senderType === 'admin' ? 'background: #f1f5f9; color: #0f172a; border-bottom-left-radius: 4px;' : 'background: #2563eb; color: #ffffff; border-bottom-right-radius: 4px;'}">${escapeHtml(messageText)}</div>
                <div class="message-time" style="font-size: 11px; color: #94a3b8; padding: 0 4px;">${timeString}</div>
            </div>
        `;

        // Remove empty chat message if exists
        const emptyChat = chatMessages.querySelector('.empty-chat');
        if (emptyChat) {
            emptyChat.remove();
        }

        chatMessages.appendChild(messageDiv);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
</script>
{% endblock %}

{% block extra_css %}
<style>
    .status-low { background: rgba(148, 163, 184, 0.16); color: #64748b; }
    .status-medium { background: rgba(59, 130, 246, 0.16); color: #2563eb; }
    .status-high { background: rgba(245, 158, 11, 0.16); color: #d97706; }
    .status-urgent { background: rgba(239, 68, 68, 0.16); color: #dc2626; }
    .status-open { background: rgba(34, 197, 94, 0.16); color: #15803d; }
    .status-in-progress { background: rgba(14, 165, 233, 0.16); color: #0369a1; }
    .status-resolved { background: rgba(168, 85, 247, 0.16); color: #7c3aed; }
    .status-closed { background: rgba(148, 163, 184, 0.16); color: #64748b; }
</style>
{% endblock %}

