{% extends "base.html" %}
{% load static %}

{% block title %}{{ source.name }} - Source Details{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="h3 mb-0">{{ source.name }}</h1>
                <div class="btn-group">
                    <a href="{% url 'source_update' source.pk %}" class="btn btn-outline-secondary">
                        <i class="fas fa-edit"></i> Edit
                    </a>
                    {% comment %} <a href="{% url 'generate_api_keys' source.pk %}" class="btn btn-warning">
                        <i class="fas fa-key"></i> Generate Keys
                    </a> {% endcomment %}
                    <button id="toggle-source-status"
                            type="button"
                            class="btn btn-outline-{{ source.is_active|yesno:'warning,success' }}"
                            hx-post="{% url 'toggle_source_status' source.pk %}"
                            hx-target="#toggle-source-status"
                            hx-select="#toggle-source-status"
                            hx-select-oob="#source-status"
                            hx-swap="outerHTML"
                            hx-confirm="Are you sure you want to {{ source.is_active|yesno:'deactivate,activate' }} this source?"
                            title="{{ source.is_active|yesno:'Deactivate,Activate' }}">
                        <i class="fas fa-{{ source.is_active|yesno:'pause,play' }}"></i>
                        {{ source.is_active|yesno:'Deactivate,Activate' }}
                    </button>
                    <a href="{% url 'source_delete' source.pk %}" class="btn btn-outline-danger">
                        <i class="fas fa-trash"></i> Delete
                    </a>
                </div>
            </div>

            <!-- Source Information -->
            <div class="row">
                <div class="col-md-8">
                    <div class="card mb-4">
                        <div class="card-header">
                            <h6 class="mb-0">Source Information</h6>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label text-muted">Name</label>
                                        <div class="fw-bold">{{ source.name }}</div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label text-muted">Type</label>
                                        <div>
                                            <span class="badge bg-info">{{ source.get_source_type_display }}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {% if source.description %}
                                <div class="mb-3">
                                    <label class="form-label text-muted">Description</label>
                                    <div>{{ source.description|linebreaks }}</div>
                                </div>
                            {% endif %}

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label text-muted">Contact Email</label>
                                        <div>
                                            {% if source.contact_email %}
                                                <a href="mailto:{{ source.contact_email }}">{{ source.contact_email }}</a>
                                            {% else %}
                                                <span class="text-muted">Not specified</span>
                                            {% endif %}
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label text-muted">Contact Phone</label>
                                        <div>
                                            {% if source.contact_phone %}
                                                {{ source.contact_phone }}
                                            {% else %}
                                                <span class="text-muted">Not specified</span>
                                            {% endif %}
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label text-muted">Status</label>
                                        <div id="source-status">
                                            {% if source.is_active %}
                                                <span class="badge bg-success">Active</span>
                                            {% else %}
                                                <span class="badge bg-secondary">Inactive</span>
                                            {% endif %}
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label text-muted">Requires Authentication</label>
                                        <div>
                                            {% if source.requires_auth %}
                                                <span class="badge bg-warning">Yes</span>
                                            {% else %}
                                                <span class="badge bg-secondary">No</span>
                                            {% endif %}
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {% if source.webhook_url %}
                                <div class="mb-3">
                                    <label class="form-label text-muted">Webhook URL</label>
                                    <div><code>{{ source.webhook_url }}</code></div>
                                </div>
                            {% endif %}

                            {% if source.api_timeout %}
                                <div class="mb-3">
                                    <label class="form-label text-muted">API Timeout</label>
                                    <div>{{ source.api_timeout }} seconds</div>
                                </div>
                            {% endif %}

                            {% if source.notes %}
                                <div class="mb-3">
                                    <label class="form-label text-muted">Notes</label>
                                    <div>{{ source.notes|linebreaks }}</div>
                                </div>
                            {% endif %}

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label text-muted">Created</label>
                                        <div>{{ source.created_at|date:"M d, Y H:i" }}</div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label text-muted">Last Updated</label>
                                        <div>{{ source.updated_at|date:"M d, Y H:i" }}</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-4">
                    <!-- API Credentials -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h6 class="mb-0">API Credentials</h6>
                        </div>
                        <div id="api-credentials" class="card-body">
                            <div class="mb-3">
                                <label class="form-label text-muted">API Key</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" value="{{ source.api_key }}" readonly>
                                    <button type="button" class="btn btn-outline-secondary"
                                            hx-post="{% url 'copy_to_clipboard' %}"
                                            hx-vals='{"text": "{{ source.api_key }}"}'
                                            title="Copy to clipboard">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label text-muted">API Secret</label>
                                <div class="input-group">
                                    <input type="password" class="form-control" value="{{ source.api_secret }}" readonly id="api-secret">
                                    <button type="button" class="btn btn-outline-secondary" onclick="toggleSecretVisibility()">
                                        <i class="fas fa-eye" id="secret-toggle-icon"></i>
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary"
                                            hx-post="{% url 'copy_to_clipboard' %}"
                                            hx-vals='{"text": "{{ source.api_secret }}"}'
                                            title="Copy to clipboard">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="text-end">
                                <a hx-post="{% url 'generate_api_keys' source.pk %}" hx-target="#api-credentials" hx-select="#api-credentials" hx-swap="outerHTML" class="btn btn-main-action btn-sm">
                                    <i class="fas fa-key"></i> Generate New Keys
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h6 class="mb-0">Integration Statistics</h6>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label text-muted">Total API Calls</label>
                                <div class="h5 mb-0">{{ total_logs }}</div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label text-muted">Successful Calls</label>
                                <div class="h5 mb-0 text-success">{{ successful_logs }}</div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label text-muted">Failed Calls</label>
                                <div class="h5 mb-0 text-danger">{{ failed_logs }}</div>
                            </div>
                            {% if total_logs > 0 %}
                                <div class="mb-3">
                                    <label class="form-label text-muted">Success Rate</label>
                                    <div class="h5 mb-0">
                                        {% widthratio successful_logs total_logs 100 %}%
                                    </div>
                                </div>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>

            <!-- Integration Logs -->
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">Recent Integration Logs</h6>
                    <small class="text-muted">Last 10 logs</small>
                </div>
                <div class="card-body">
                    {% if integration_logs %}
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead class="table-light">
                                    <tr>
                                        <th>Timestamp</th>
                                        <th>Method</th>
                                        <th>Status</th>
                                        <th>Response Time</th>
                                        <th>Details</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for log in integration_logs %}
                                        <tr>
                                            <td>
                                                <small>{{ log.created_at|date:"M d, Y H:i:s" }}</small>
                                            </td>
                                            <td>
                                                <span class="badge bg-secondary">{{ log.method }}</span>
                                            </td>
                                            <td>
                                                {% if log.status_code >= 200 and log.status_code < 300 %}
                                                    <span class="badge bg-success">{{ log.status_code }}</span>
                                                {% elif log.status_code >= 400 %}
                                                    <span class="badge bg-danger">{{ log.status_code }}</span>
                                                {% else %}
                                                    <span class="badge bg-warning">{{ log.status_code }}</span>
                                                {% endif %}
                                            </td>
                                            <td>
                                                {% if log.response_time_ms %}
                                                    <small>{{ log.response_time_ms }}ms</small>
                                                {% else %}
                                                    <span class="text-muted">-</span>
                                                {% endif %}
                                            </td>
                                            <td>
                                                {% if log.request_data %}
                                                    <button type="button" class="btn btn-sm btn-outline-info"
                                                            data-bs-toggle="modal"
                                                            data-bs-target="#logDetailModal{{ log.id }}"
                                                            title="View details">
                                                        <i class="fas fa-eye"></i>
                                                    </button>
                                                {% else %}
                                                    <span class="text-muted">No data</span>
                                                {% endif %}
                                            </td>
                                        </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    {% else %}
                        <div class="text-center py-4">
                            <i class="fas fa-clipboard-list fa-2x text-muted mb-3"></i>
                            <p class="text-muted">No integration logs found</p>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Log Detail Modals -->
{% for log in integration_logs %}
    {% if log.request_data %}
        <div class="modal fade" id="logDetailModal{{ log.id }}" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Integration Log Details</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <strong>Timestamp:</strong><br>
                                {{ log.created_at|date:"M d, Y H:i:s" }}
                            </div>
                            <div class="col-md-6">
                                <strong>Method:</strong><br>
                                <span class="badge bg-secondary">{{ log.method }}</span>
                            </div>
                        </div>
                        <hr>
                        <div class="row">
                            <div class="col-md-6">
                                <strong>Status Code:</strong><br>
                                {% if log.status_code >= 200 and log.status_code < 300 %}
                                    <span class="badge bg-success">{{ log.status_code }}</span>
                                {% elif log.status_code >= 400 %}
                                    <span class="badge bg-danger">{{ log.status_code }}</span>
                                {% else %}
                                    <span class="badge bg-warning">{{ log.status_code }}</span>
                                {% endif %}
                            </div>
                            <div class="col-md-6">
                                <strong>Response Time:</strong><br>
                                {% if log.response_time_ms %}
                                    {{ log.response_time_ms }}ms
                                {% else %}
                                    -
                                {% endif %}
                            </div>
                        </div>
                        <hr>
                        <div class="mb-3">
                            <strong>Request Data:</strong>
                            <pre class="bg-light p-2 rounded"><code>{{ log.request_data|pprint }}</code></pre>
                        </div>
                        {% if log.response_data %}
                            <div class="mb-3">
                                <strong>Response Data:</strong>
                                <pre class="bg-light p-2 rounded"><code>{{ log.response_data|pprint }}</code></pre>
                            </div>
                        {% endif %}
                        {% if log.error_message %}
                            <div class="mb-3">
                                <strong>Error Message:</strong>
                                <div class="alert alert-danger">{{ log.error_message }}</div>
                            </div>
                        {% endif %}
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    {% endif %}
{% endfor %}
{% endblock %}

{% block customJS %}
<script>
function toggleSecretVisibility() {
    const secretInput = document.getElementById('api-secret');
    const toggleIcon = document.getElementById('secret-toggle-icon');

    if (secretInput.type === 'password') {
        secretInput.type = 'text';
        toggleIcon.classList.remove('fa-eye');
        toggleIcon.classList.add('fa-eye-slash');
    } else {
        secretInput.type = 'password';
        toggleIcon.classList.remove('fa-eye-slash');
        toggleIcon.classList.add('fa-eye');
    }
}

// Handle HTMX copy to clipboard feedback
document.body.addEventListener('htmx:afterRequest', function(evt) {
    if (evt.detail.successful && evt.detail.target.matches('[hx-post*="copy_to_clipboard"]')) {
        const button = evt.detail.target;
        const originalIcon = button.innerHTML;
        button.innerHTML = '<i class="fas fa-check"></i>';
        button.classList.remove('btn-outline-secondary');
        button.classList.add('btn-success');

        setTimeout(() => {
            button.innerHTML = originalIcon;
            button.classList.remove('btn-success');
            button.classList.add('btn-outline-secondary');
        }, 2000);
    }
});

// Auto-refresh after status toggle
document.body.addEventListener('htmx:afterRequest', function(evt) {
    if (evt.detail.successful && evt.detail.target.matches('[hx-post*="toggle_source_status"]')) {
        // Reload the page after a short delay to show updated status
        setTimeout(() => {
            window.location.reload();
        }, 500);
    }
});
</script>
{% endblock %}
