{% extends "base.html" %}

{% block content %}
    <h1>Manage Assessments</h1>
    <a href="{{ url_for('admin.create_assessment') }}" class="btn btn-primary mb-3">Create New Assessment</a>
    <table class="table table-striped">
        <thead>
            <tr>
                <th>Name</th>
                <th>Description</th>
                <th>Type</th>
                <th>Free</th>
                <th>Price</th>
                <th>Min Qty</th>
                <th>Actions</th>
                <th>Assign to Client</th>
            </tr>
        </thead>
        <tbody>
            {% for assessment in assessments %}
            <tr>
                <td>{{ assessment.name }}</td>
                <td>{{ assessment.description }}</td>
                <td>{{ assessment.assessment_type }}</td>
                <td>{{ 'Yes' if assessment.is_free else 'No' }}</td>
                <td>{{ '₹' + assessment.price|string if not assessment.is_free else 'Free' }}</td>
                <td>{{ assessment.min_quantity if not assessment.is_free else '-' }}</td>
                <td>
                    <a href="{{ url_for('admin.manage_questions', assessment_id=assessment.id) }}" class="btn btn-sm btn-info">Manage Questions</a>
                    <a href="{{ url_for('admin.edit_assessment', assessment_id=assessment.id) }}" class="btn btn-sm btn-warning">Edit</a>
                    <form method="POST" action="{{ url_for('admin.delete_assessment', assessment_id=assessment.id) }}" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this assessment?');">
                        <button type="submit" class="btn btn-sm btn-danger">Delete</button>
                    </form>
                </td>
                <td>
                    <!-- Button to trigger modal -->
                    <button type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#generateLinkModal-{{ assessment.id }}">
                        Generate Link
                    </button>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>

    <!-- Modals for each assessment -->
    {% for assessment in assessments %}
    <div class="modal fade" id="generateLinkModal-{{ assessment.id }}" tabindex="-1" role="dialog" aria-labelledby="generateLinkModalLabel-{{ assessment.id }}" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="generateLinkModalLabel-{{ assessment.id }}">Generate Link for {{ assessment.name }}</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="recipient-email-{{ assessment.id }}">Client's Email</label>
                        <input type="email" class="form-control" id="recipient-email-{{ assessment.id }}" placeholder="Enter client's email">
                    </div>
                    <button type="button" class="btn btn-primary" onclick="generateLink('{{ assessment.id }}')">Generate</button>
                    <hr>
                    <div id="link-result-{{ assessment.id }}" style="display:none;">
                        <strong>Generated Link:</strong>
                        <div class="input-group mt-2">
                            <input type="text" class="form-control" id="generated-link-{{ assessment.id }}" readonly>
                            <div class="input-group-append">
                                <button class="btn btn-outline-secondary" type="button" onclick="copyLink('{{ assessment.id }}')">Copy</button>
                            </div>
                        </div>
                        <small class="form-text text-muted">You can now copy this link and send it to your client.</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% endfor %}
{% endblock %}

{% block scripts %}
<script>
    function generateLink(assessmentId) {
        const email = document.getElementById(`recipient-email-${assessmentId}`).value;
        // Email is optional now

        // This assumes you have an admin blueprint. Adjust if necessary.
        fetch(`{{ url_for('admin.generate_assessment_link') }}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                assessment_id: assessmentId,
                email: email
            }),
        })
        .then(response => {
            if (response.redirected) {
                // If the server redirected us (e.g. to login), reload the page to follow it
                window.location.reload();
                return; 
            }
            if (!response.ok) {
                return response.text().then(text => {
                     let errorMsg = `Server returned ${response.status}`;
                     try {
                        const json = JSON.parse(text);
                        if (json.error) {
                            throw new Error(json.error);
                        }
                     } catch(e) {
                        // If it was our error from above, rethrow it
                        if (e.message !== 'Unexpected token < in JSON at position 0' && !e.message.includes('JSON')) {
                             throw e; 
                        }
                        // Otherwise, if text is short, use it
                        if (text.length < 200) {
                            throw new Error(text);
                        }
                     }
                     throw new Error(errorMsg);
                });
            }
            // Check if content-type is JSON
            const contentType = response.headers.get("content-type");
            if (!contentType || !contentType.includes("application/json")) {
                return response.text().then(text => {
                    console.error("Received non-JSON response:", text);
                    throw new Error("Server returned invalid response format (HTML instead of JSON). Check console for details.");
                });
            }
            return response.json();
        })
        .then(data => {
            if (data.link) {
                const linkResultDiv = document.getElementById(`link-result-${assessmentId}`);
                const linkInput = document.getElementById(`generated-link-${assessmentId}`);
                linkInput.value = data.link;
                linkResultDiv.style.display = 'block';
            } else {
                alert('Error: ' + (data.error || 'Could not generate link.'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error: ' + error.message);
        });
    }

    function copyLink(assessmentId) {
        const linkInput = document.getElementById(`generated-link-${assessmentId}`);
        linkInput.select();
        document.execCommand('copy');
        alert('Link copied to clipboard!');
    }
</script>
{% endblock %}
