{% extends "base.html" %}

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

{% block content %}
<div class="container-fluid">
    {% from "_components.html" import page_header %}
    <div class="row">
        <div class="col-12">
            {% set actions %}
            {% if current_user.is_admin %}
            <a href="{{ url_for('projects.create_project') }}" class="btn btn-outline-light btn-sm">
                <i class="fas fa-plus"></i> New Project
            </a>
            {% endif %}
            {% endset %}
            {{ page_header('fas fa-project-diagram', 'Projects', 'Manage all projects • ' ~ (projects|length) ~ ' total', actions) }}
        </div>
    </div>

    {# Summary cards similar to invoices #}
    {% set _active = 0 %}
    {% set _archived = 0 %}
    {% set _total_hours = 0 %}
    {% for p in projects %}
        {% if p.status == 'active' %}{% set _active = _active + 1 %}{% endif %}
        {% if p.status == 'archived' %}{% set _archived = _archived + 1 %}{% endif %}
        {% set _total_hours = _total_hours + (p.total_hours or 0) %}
    {% endfor %}
    <div class="row mb-4">
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card border-0 shadow-sm h-100 summary-card">
                <div class="card-body p-3 d-flex align-items-center">
                    <div class="summary-icon bg-primary bg-opacity-10 text-primary"><i class="fas fa-list"></i></div>
                    <div class="ms-3">
                        <div class="summary-label">Total Projects</div>
                        <div class="summary-value">{{ projects|length }}</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card border-0 shadow-sm h-100 summary-card">
                <div class="card-body p-3 d-flex align-items-center">
                    <div class="summary-icon bg-success bg-opacity-10 text-success"><i class="fas fa-check-circle"></i></div>
                    <div class="ms-3">
                        <div class="summary-label">Active</div>
                        <div class="summary-value">{{ _active }}</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card border-0 shadow-sm h-100 summary-card">
                <div class="card-body p-3 d-flex align-items-center">
                    <div class="summary-icon bg-secondary bg-opacity-10 text-secondary"><i class="fas fa-archive"></i></div>
                    <div class="ms-3">
                        <div class="summary-label">Archived</div>
                        <div class="summary-value">{{ _archived }}</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card border-0 shadow-sm h-100 summary-card">
                <div class="card-body p-3 d-flex align-items-center">
                    <div class="summary-icon bg-info bg-opacity-10 text-info"><i class="fas fa-hourglass-half"></i></div>
                    <div class="ms-3">
                        <div class="summary-label">Total Hours</div>
                        <div class="summary-value">{{ '%.1f'|format(_total_hours) }}h</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card mobile-card">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-filter me-2 text-primary"></i>Filters
                    </h6>
                </div>
                <div class="card-body">
                    <form method="GET" class="row g-3 mobile-form">
                        <div class="col-12 col-md-4 mobile-form-group">
                            <label for="status" class="form-label">Status</label>
                            <select class="form-select touch-target" id="status" name="status">
                                <option value="">All Statuses</option>
                                <option value="active" {% if request.args.get('status') == 'active' %}selected{% endif %}>Active</option>
                                <option value="archived" {% if request.args.get('status') == 'archived' %}selected{% endif %}>Archived</option>
                            </select>
                        </div>
                        <div class="col-12 col-md-4 mobile-form-group">
                            <label for="client" class="form-label">Client</label>
                            <select class="form-select touch-target" id="client" name="client">
                                <option value="">All Clients</option>
                                {% for client in clients %}
                                <option value="{{ client }}" {% if request.args.get('client') == client %}selected{% endif %}>{{ client }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-12 col-md-4 mobile-form-group">
                            <label for="search" class="form-label">Search</label>
                            <input type="text" class="form-control touch-target" id="search" name="search" 
                                   value="{{ request.args.get('search', '') }}" placeholder="Project name or description">
                        </div>
                        <div class="col-12 d-flex flex-column flex-md-row gap-2 mobile-stack">
                            <button type="submit" class="btn btn-primary mobile-btn flex-fill">
                                <i class="fas fa-search me-1"></i>Filter
                            </button>
                            <a href="{{ url_for('projects.list_projects') }}" class="btn btn-outline-secondary mobile-btn flex-fill">
                                <i class="fas fa-times me-1"></i>Clear
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Projects List -->
    <div class="row">
        <div class="col-12">
            <div class="card shadow-sm border-0 mobile-card">
                <div class="card-header bg-white py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <h6 class="m-0 font-weight-bold text-primary">
                            <i class="fas fa-list me-2"></i>All Projects
                        </h6>
                        <div class="d-flex gap-2">
                            <div class="input-group input-group-sm" style="width: 250px;">
                                <span class="input-group-text bg-light border-end-0">
                                    <i class="fas fa-search text-muted"></i>
                                </span>
                                <input type="text" class="form-control border-start-0" id="searchInput" 
                                       placeholder="Search projects...">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-body p-0">
                    {% if projects %}
                    <div class="table-responsive">
                        <table class="table table-hover mb-0" id="projectsTable">
                            <thead class="table-light">
                                <tr>
                                    <th class="border-0">Project</th>
                                    <th class="border-0">Client</th>
                                    <th class="border-0">Status</th>
                                    <th class="border-0">Hours</th>
                                    <th class="border-0">Rate</th>
                                    <th class="border-0 text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for project in projects %}
                                <tr>
                                    <td data-label="Project">
                                        <div>
                                            <a href="{{ url_for('projects.view_project', project_id=project.id) }}" class="text-decoration-none">
                                                <strong>{{ project.name }}</strong>
                                            </a>
                                            {% if project.description %}
                                            <br><small class="text-muted">{{ project.description[:100] }}{% if project.description|length > 100 %}...{% endif %}</small>
                                            {% endif %}
                                        </div>
                                    </td>
                                    <td data-label="Client">
                                        <span class="project-badge">{{ project.client }}</span>
                                    </td>
                                    <td data-label="Status">
                                        {% if project.status == 'active' %}
                                        <span class="status-badge bg-success text-white">Active</span>
                                        {% else %}
                                        <span class="status-badge bg-secondary text-white">Archived</span>
                                        {% endif %}
                                    </td>
                                    <td data-label="Hours" class="align-middle" style="min-width:180px;">
                                        {% set total_h = (project.total_hours or 0) %}
                                        {% set billable_h = (project.billable_hours or 0) %}
                                        {% set pct = (billable_h / total_h * 100) if total_h > 0 else 0 %}
                                        <div class="d-flex justify-content-between align-items-center mb-1">
                                            <strong>{{ "%.1f"|format(total_h) }} h</strong>
                                            <small class="text-success">{{ "%.1f"|format(billable_h) }} h billable</small>
                                        </div>
                                        <div class="progress bg-light rounded-pill" style="height:6px;">
                                            <div class="progress-bar bg-success rounded-pill" role="progressbar" data-pct="{{ pct|round(0, 'floor') }}" aria-valuenow="{{ pct|round(0, 'floor') }}" aria-valuemin="0" aria-valuemax="100"></div>
                                        </div>
                                    </td>
                                    <td data-label="Rate" class="text-end">
                                        {% if project.hourly_rate %}
                                        <span class="badge bg-primary-subtle text-primary border border-primary-subtle rounded-pill">{{ currency }}{{ "%.2f"|format(project.hourly_rate) }}/h</span>
                                        {% else %}
                                        <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td class="actions-cell" data-label="Actions">
                                        <div class="btn-group btn-group-sm" role="group">
                                            <a href="{{ url_for('projects.view_project', project_id=project.id) }}" 
                                               class="btn btn-sm btn-action btn-action--view touch-target" title="View project">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            {% if current_user.is_admin %}
                                            <a href="{{ url_for('projects.edit_project', project_id=project.id) }}" 
                                               class="btn btn-sm btn-action btn-action--edit touch-target" title="Edit project">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <button type="button" class="btn btn-sm btn-action btn-action--danger touch-target" title="Delete project"
                                                    onclick="showDeleteProjectModal('{{ project.id }}', '{{ project.name }}')">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    {% else %}
                    <div class="text-center py-5">
                        <div class="empty-state">
                            <i class="fas fa-project-diagram fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">No projects found</h5>
                            <p class="text-muted mb-4">Create your first project to get started.</p>
                            {% if current_user.is_admin %}
                            <a href="{{ url_for('projects.create_project') }}" class="btn btn-primary touch-target">
                                <i class="fas fa-plus me-2"></i> Create Project
                            </a>
                            {% endif %}
                        </div>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Delete Project Modal -->
<div class="modal fade" id="deleteProjectModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-trash me-2 text-danger"></i>Delete Project
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>Warning:</strong> This action cannot be undone.
                </div>
                <p>Are you sure you want to delete the project <strong id="deleteProjectName"></strong>?</p>
                <p class="text-muted mb-0">All associated time entries will also be deleted.</p>
            </div>
            <div class="modal-footer d-flex flex-column flex-md-row">
                <button type="button" class="btn btn-secondary mb-2 mb-md-0 me-md-2 touch-target" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i>Cancel
                </button>
                <form method="POST" id="deleteProjectForm" class="d-inline">
                    <button type="submit" class="btn btn-danger touch-target">
                        <i class="fas fa-trash me-2"></i>Delete Project
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<style>
.summary-card {
    transition: all 0.3s ease;
    border-radius: 12px;
}

.summary-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
}

.summary-icon {
    width: 44px;
    height: 44px;
    border-radius: 10px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
}

.summary-label {
    font-size: 12px;
    font-weight: 600;
    color: var(--text-secondary);
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.summary-value {
    font-size: 20px;
    font-weight: 800;
    color: var(--text-primary);
}

.project-badge {
    background: var(--light-color);
    color: var(--text-secondary);
    padding: 4px 8px;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 500;
}

.status-badge {
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.empty-state {
    padding: 2rem;
}

@media (max-width: 768px) {
    .summary-card { margin-bottom: 1rem; }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize DataTable
    const table = $('#projectsTable').DataTable({
        order: [[0, 'asc']],
        pageLength: 25,
        responsive: true,
        dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
             '<"row"<"col-sm-12"tr>>' +
             '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
        columnDefs: [
            { orderable: false, targets: -1 }
        ]
    });

    // Custom search
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchInput.addEventListener('keyup', function() {
            table.search(this.value).draw();
        });
    }

    // Fill progress bars
    document.querySelectorAll('#projectsTable .progress-bar').forEach(el => {
        const pct = el.getAttribute('data-pct') || 0;
        el.style.width = pct + '%';
    });
});

function filterByStatus(status) {
    const table = $('#projectsTable').DataTable();
    if (status === 'all') {
        table.column(2).search('').draw();
    } else {
        // Match the rendered badge text
        const regex = status === 'active' ? '^Active$' : '^Archived$';
        table.column(2).search(regex, true, false).draw();
    }
    document.querySelectorAll('.dropdown-item').forEach(i => i.classList.remove('active'));
    const active = document.querySelector(`[onclick="filterByStatus('${status}')"]`);
    if (active) active.classList.add('active');
}

// Function to show delete project modal
function showDeleteProjectModal(projectId, projectName) {
    document.getElementById('deleteProjectName').textContent = projectName;
    document.getElementById('deleteProjectForm').action = "{{ url_for('projects.delete_project', project_id=0) }}".replace('0', projectId);
    new bootstrap.Modal(document.getElementById('deleteProjectModal')).show();
}

// Add loading state to delete project form
document.addEventListener('DOMContentLoaded', function() {
    const deleteForm = document.getElementById('deleteProjectForm');
    if (deleteForm) {
        deleteForm.addEventListener('submit', function() {
            const submitBtn = this.querySelector('button[type="submit"]');
            submitBtn.innerHTML = '<div class="loading-spinner me-2"></div>Deleting...';
            submitBtn.disabled = true;
        });
    }
});
</script>
{% endblock %}
