{% extends "base.html" %}

{% block title %}Projects - AtlasUI{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <!-- Breadcrumb -->
        <nav aria-label="breadcrumb" class="mb-2">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="/organizations">Organizations</a></li>
                <li class="breadcrumb-item active" aria-current="page"><span id="orgNameBreadcrumb">...</span></li>
            </ol>
        </nav>

        <div class="d-flex justify-content-between align-items-center mb-2">
            <h1><i class="bi bi-folder"></i> Projects</h1>
            <button class="btn btn-outline-success btn-sm" id="refreshBtn">
                <i class="bi bi-arrow-clockwise"></i> Refresh
            </button>
        </div>

        <script>
            const ORG_ID_OR_NAME = "{{ org_id_or_name }}";
        </script>

        <!-- Loading indicator -->
        <div id="loadingIndicator" class="text-center my-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">Loading projects...</p>
        </div>

        <!-- Error message -->
        <div id="errorMessage" class="alert alert-danger d-none" role="alert">
            <i class="bi bi-exclamation-triangle"></i>
            <span id="errorText"></span>
        </div>

        <!-- Projects grouped by organization -->
        <div id="projectsTable" class="d-none">
            <div id="projectsContainer">
            </div>
        </div>
    </div>
</div>

<!-- Details Panel (Offcanvas) -->
<div class="offcanvas offcanvas-end offcanvas-wide" tabindex="-1" id="detailsPanel" aria-labelledby="detailsPanelLabel">
    <div class="offcanvas-header border-bottom">
        <h5 class="offcanvas-title" id="detailsPanelLabel">
            <i class="bi bi-info-circle"></i> Project Details
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
    </div>
    <div class="offcanvas-body">
        <div id="detailsContent">
            <p class="text-muted">Click on a project name to view its details</p>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="deleteConfirmModalLabel">
                    <i class="bi bi-exclamation-triangle"></i> Confirm Project Deletion
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-danger mb-3">
                    <strong>Warning!</strong> This action cannot be undone. Deleting this project will permanently remove:
                </div>

                <h6>Project: <strong id="deleteProjectName"></strong></h6>

                <div id="deleteResourcesLoading" class="text-center my-3">
                    <div class="spinner-border spinner-border-sm text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="small mt-2">Loading project resources...</p>
                </div>

                <div id="deleteResourcesList" class="d-none">
                    <h6 class="mt-3">Clusters to be deleted:</h6>
                    <div id="deleteClustersContainer"></div>

                    <div class="mt-3 p-3 bg-light border rounded">
                        <p class="mb-2"><strong>To confirm deletion, type the project name exactly as shown above:</strong></p>
                        <input type="text" class="form-control" id="deleteConfirmInput" placeholder="Type project name here">
                        <div id="deleteConfirmError" class="text-danger small mt-1 d-none">Project name does not match</div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="deleteConfirmBtn" disabled onclick="executeDeleteProject()">
                    <i class="bi bi-trash"></i> Delete Project
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<style>
    h1 {
        font-size: 1.25rem;
    }

    .offcanvas-wide {
        width: 600px !important;
        max-width: 90vw;
    }

    .project-name-link {
        cursor: pointer;
        color: #00684a;
        text-decoration: none;
    }

    .project-name-link:hover {
        text-decoration: underline;
    }
</style>

<script>
let projects = [];

document.addEventListener('DOMContentLoaded', function() {
    loadProjects();
    document.getElementById('refreshBtn').addEventListener('click', loadProjects);
});

async function loadProjects() {
    const loading = document.getElementById('loadingIndicator');
    const error = document.getElementById('errorMessage');
    const table = document.getElementById('projectsTable');

    loading.classList.remove('d-none');
    error.classList.add('d-none');
    table.classList.add('d-none');

    try {
        // Fetch all organizations to find the matching one
        const orgsResponse = await fetch('/api/organizations/');
        if (!orgsResponse.ok) throw new Error('Failed to fetch organizations');
        const orgsData = await orgsResponse.json();

        // Find organization by ID or name (case-sensitive)
        const org = (orgsData.results || []).find(o =>
            o.id === ORG_ID_OR_NAME || o.name === ORG_ID_OR_NAME
        );

        if (!org) {
            throw new Error(`Organization "${ORG_ID_OR_NAME}" not found`);
        }

        // Update breadcrumb with organization name
        const breadcrumb = document.getElementById('orgNameBreadcrumb');
        breadcrumb.textContent = org.name;

        // Fetch projects for this organization
        const projectsResponse = await fetch(`/api/organizations/${org.id}/projects?itemsPerPage=500`);
        if (!projectsResponse.ok) throw new Error('Failed to fetch projects');
        const projectsData = await projectsResponse.json();

        projects = projectsData.results || [];

        renderProjects();
        loading.classList.add('d-none');
        table.classList.remove('d-none');

    } catch (err) {
        console.error('Error loading projects:', err);
        loading.classList.add('d-none');
        error.classList.remove('d-none');
        document.getElementById('errorText').textContent = err.message;
    }
}

function renderProjects() {
    const container = document.getElementById('projectsContainer');
    container.innerHTML = '';

    if (projects.length === 0) {
        container.innerHTML = '<div class="alert alert-info">No projects found in this organization</div>';
        return;
    }

    // Create table for projects
    const tableDiv = document.createElement('div');
    tableDiv.className = 'table-responsive';
    tableDiv.innerHTML = `
        <table class="table table-striped table-hover">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Clusters</th>
                    <th>Created</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    `;

    const tbody = tableDiv.querySelector('tbody');

    projects.forEach(project => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>
                <a href="javascript:void(0)" class="project-name-link" onclick="showProjectDetails('${project.id}')">
                    <strong>${project.name}</strong>
                </a>
            </td>
            <td>
                <a href="/projects/${encodeURIComponent(project.name)}" class="text-decoration-none">
                    <span class="badge bg-primary">${project.clusterCount || 0}</span>
                </a>
            </td>
            <td>${new Date(project.created).toLocaleDateString()}</td>
            <td>
                <button class="btn btn-sm btn-outline-danger" onclick="confirmDeleteProject('${project.id}', '${project.name.replace(/'/g, "\\'")}')">
                    <i class="bi bi-trash"></i> Delete
                </button>
            </td>
        `;

        tbody.appendChild(row);
    });

    container.appendChild(tableDiv);
}

async function showProjectDetails(projectId) {
    // Find project in the projects array
    const project = projects.find(p => p.id === projectId);
    if (!project) return;

    const detailsContent = document.getElementById('detailsContent');

    // Show loading state
    detailsContent.innerHTML = `
        <div class="text-center my-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">Loading project details...</p>
        </div>
    `;

    // Open the offcanvas immediately
    const offcanvas = new bootstrap.Offcanvas(document.getElementById('detailsPanel'));
    offcanvas.show();

    try {
        // Fetch all related data in parallel
        const [clustersData, usersData] = await Promise.all([
            fetch(`/api/clusters/${project.id}`).then(r => r.ok ? r.json() : { results: [] }).catch(() => ({ results: [] })),
            fetch(`/api/users/${project.id}`).then(r => r.ok ? r.json() : { results: [] }).catch(() => ({ results: [] }))
        ]);

        const clusters = clustersData.results || [];
        const users = usersData.results || [];

        // Build comprehensive details HTML
        let html = `
            <h5 class="mb-3">
                <i class="bi bi-folder"></i> ${project.name}
            </h5>

            <div class="mb-3">
                <h6 class="text-muted">Basic Information</h6>
                <table class="table table-sm">
                    <tbody>
                        <tr><th>Name</th><td>${project.name}</td></tr>
                        <tr><th>ID</th><td><code class="small">${project.id}</code></td></tr>
                        <tr><th>Organization ID</th><td><code class="small">${project.orgId}</code></td></tr>
                        <tr><th>Cluster Count</th><td>${project.clusterCount || 0}</td></tr>
                        <tr><th>Database Users</th><td>${users.length}</td></tr>
                        <tr><th>Created</th><td>${new Date(project.created).toLocaleString()}</td></tr>
                        <tr><th>Default Alerts</th><td>${project.withDefaultAlertsSettings ? 'Enabled' : 'Disabled'}</td></tr>
                    </tbody>
                </table>
            </div>
        `;

        // Add tags section if available
        if (project.tags && project.tags.length > 0) {
            html += `
                <div class="mb-3">
                    <h6 class="text-muted">Tags</h6>
                    ${project.tags.map(tag => `<span class="badge bg-secondary me-1">${tag}</span>`).join('')}
                </div>
            `;
        }

        // Add clusters section
        if (clusters.length > 0) {
            html += `
                <div class="mb-3">
                    <h6 class="text-muted">Clusters (${clusters.length})</h6>
                    <div class="list-group list-group-flush">
                        ${clusters.map(cluster => `
                            <div class="list-group-item py-2 px-2">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <strong><i class="bi bi-hdd-rack"></i> ${cluster.name}</strong>
                                        <div class="small text-muted">
                                            ${cluster.clusterType || 'N/A'} •
                                            ${cluster.mongoDBVersion || 'N/A'} •
                                            ${cluster.providerSettings?.providerName || 'N/A'}
                                        </div>
                                    </div>
                                    <span class="badge ${getStatusBadgeClass(cluster.stateName)}">${cluster.stateName || 'UNKNOWN'}</span>
                                </div>
                            </div>
                        `).join('')}
                    </div>
                </div>
            `;
        } else {
            html += `
                <div class="mb-3">
                    <h6 class="text-muted">Clusters</h6>
                    <p class="small text-muted">No clusters in this project</p>
                </div>
            `;
        }

        // Add database users section
        if (users.length > 0) {
            html += `
                <div class="mb-3">
                    <h6 class="text-muted">Database Users (${users.length})</h6>
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Username</th>
                                    <th>Database</th>
                                    <th>Roles</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${users.map(user => `
                                    <tr>
                                        <td><strong>${user.username}</strong></td>
                                        <td><code class="small">${user.databaseName || 'admin'}</code></td>
                                        <td>
                                            ${user.roles && user.roles.length > 0 ?
                                                user.roles.map(role => `<span class="badge bg-secondary me-1">${role.roleName}</span>`).join('') :
                                                '<span class="text-muted">No roles</span>'
                                            }
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                </div>
            `;
        } else {
            html += `
                <div class="mb-3">
                    <h6 class="text-muted">Database Users</h6>
                    <p class="small text-muted">No database users in this project</p>
                </div>
            `;
        }

        detailsContent.innerHTML = html;

    } catch (err) {
        console.error('Error loading project details:', err);
        detailsContent.innerHTML = `
            <div class="alert alert-danger">
                <i class="bi bi-exclamation-triangle"></i>
                Failed to load project details: ${err.message}
            </div>
        `;
    }
}

function getStatusBadgeClass(status) {
    switch (status) {
        case 'IDLE':
            return 'bg-success';
        case 'CREATING':
        case 'UPDATING':
            return 'bg-warning';
        case 'DELETING':
        case 'DELETED':
            return 'bg-danger';
        case 'REPAIRING':
            return 'bg-info';
        default:
            return 'bg-secondary';
    }
}

// Delete project functionality
let deleteProjectId = null;
let deleteProjectNameExpected = null;

async function confirmDeleteProject(projectId, projectName) {
    deleteProjectId = projectId;
    deleteProjectNameExpected = projectName;

    // Reset modal state
    document.getElementById('deleteProjectName').textContent = projectName;
    document.getElementById('deleteConfirmInput').value = '';
    document.getElementById('deleteConfirmBtn').disabled = true;
    document.getElementById('deleteConfirmError').classList.add('d-none');
    document.getElementById('deleteResourcesLoading').classList.remove('d-none');
    document.getElementById('deleteResourcesList').classList.add('d-none');

    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
    modal.show();

    // Load clusters and databases
    try {
        const clustersResponse = await fetch(`/api/clusters/${projectId}`);
        const clustersData = await clustersResponse.ok ? await clustersResponse.json() : { results: [] };
        const clusters = clustersData.results || [];

        // Build clusters list with database info
        const clustersContainer = document.getElementById('deleteClustersContainer');

        if (clusters.length === 0) {
            clustersContainer.innerHTML = '<p class="text-muted">No clusters in this project</p>';
        } else {
            let html = '<ul class="list-group">';
            for (const cluster of clusters) {
                html += `
                    <li class="list-group-item">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <strong><i class="bi bi-hdd-rack"></i> ${cluster.name}</strong>
                                <div class="small text-muted">
                                    ${cluster.clusterType || 'N/A'} •
                                    ${cluster.mongoDBVersion || 'N/A'} •
                                    ${cluster.providerSettings?.providerName || 'N/A'}
                                </div>
                                <div class="small text-muted mt-1">
                                    <strong>Note:</strong> All databases and collections in this cluster will be permanently deleted
                                </div>
                            </div>
                            <span class="badge ${getStatusBadgeClass(cluster.stateName)}">${cluster.stateName || 'UNKNOWN'}</span>
                        </div>
                    </li>
                `;
            }
            html += '</ul>';
            clustersContainer.innerHTML = html;
        }

        // Hide loading, show resources
        document.getElementById('deleteResourcesLoading').classList.add('d-none');
        document.getElementById('deleteResourcesList').classList.remove('d-none');

    } catch (err) {
        console.error('Error loading project resources:', err);
        document.getElementById('deleteResourcesLoading').innerHTML = `
            <div class="alert alert-warning">
                <i class="bi bi-exclamation-triangle"></i>
                Failed to load project resources. You can still proceed with deletion.
            </div>
        `;
        document.getElementById('deleteResourcesList').classList.remove('d-none');
    }
}

// Validate project name input
document.addEventListener('DOMContentLoaded', function() {
    const input = document.getElementById('deleteConfirmInput');
    const btn = document.getElementById('deleteConfirmBtn');
    const error = document.getElementById('deleteConfirmError');

    input.addEventListener('input', function() {
        const value = input.value.trim();
        if (value === deleteProjectNameExpected) {
            btn.disabled = false;
            error.classList.add('d-none');
        } else {
            btn.disabled = true;
            if (value.length > 0) {
                error.classList.remove('d-none');
            } else {
                error.classList.add('d-none');
            }
        }
    });
});

async function executeDeleteProject() {
    if (!deleteProjectId) return;

    const btn = document.getElementById('deleteConfirmBtn');
    const originalHtml = btn.innerHTML;

    // Show loading state
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Deleting...';

    try {
        const response = await fetch(`/api/projects/${deleteProjectId}`, {
            method: 'DELETE'
        });

        let errorMessage = 'Failed to delete project';

        if (!response.ok) {
            try {
                const error = await response.json();
                errorMessage = error.detail || errorMessage;
            } catch (parseError) {
                // If response is not JSON, use status text
                errorMessage = `${errorMessage}: ${response.statusText || response.status}`;
            }
            throw new Error(errorMessage);
        }

        const result = await response.json();

        // Close modal
        const modal = bootstrap.Modal.getInstance(document.getElementById('deleteConfirmModal'));
        modal.hide();

        // Show success message
        const successAlert = document.createElement('div');
        successAlert.className = 'alert alert-success alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-3';
        successAlert.style.zIndex = '9999';
        successAlert.innerHTML = `
            <i class="bi bi-check-circle"></i> Project "${deleteProjectNameExpected}" has been deleted successfully
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        document.body.appendChild(successAlert);
        setTimeout(() => successAlert.remove(), 5000);

        // Reload projects list
        loadProjects();

    } catch (err) {
        console.error('Error deleting project:', err);

        // Show error in a more visible way
        const errorAlert = document.createElement('div');
        errorAlert.className = 'alert alert-danger alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-3';
        errorAlert.style.zIndex = '9999';
        errorAlert.innerHTML = `
            <i class="bi bi-exclamation-triangle"></i> <strong>Failed to delete project:</strong><br>
            ${err.message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        document.body.appendChild(errorAlert);

        // Re-enable button
        btn.disabled = false;
        btn.innerHTML = originalHtml;

        // Keep modal open so user can try again
    }
}
</script>
{% endblock %}
