{% extends "base.html" %}

{% block title %}{{ model_name }} - CREATESONLINE Admin{% endblock %}

{% block breadcrumbs %}
<div class="breadcrumbs">
    <a href="/admin/">Home</a>
    <span class="separator">/</span>
    <span>{{ model_name }}</span>
</div>
{% endblock %}

{% block content %}
<div class="model-header">
    <h1>{{ model_verbose_name|default:model_name }}</h1>
    <div class="model-actions">
        <button class="btn btn-primary" onclick="window.location.href='/admin/{{ model_name }}/create'">
            Add {{ model_verbose_name|default:model_name }}
        </button>
        <button class="btn btn-secondary" onclick="exportData()">
            Export
        </button>
    </div>
</div>

<div class="filters-section">
    <div class="search-box">
        <input type="text" id="searchInput" placeholder="Search..." class="form-control">
    </div>
    <div class="filter-actions">
        <button class="btn btn-sm" onclick="applyFilters()">Apply Filters</button>
        <button class="btn btn-sm btn-secondary" onclick="clearFilters()">Clear</button>
    </div>
</div>

<div class="table-container">
    <table class="admin-table" id="dataTable">
        <thead>
            <tr>
                <th><input type="checkbox" id="selectAll"></th>
                {% for field in fields %}
                <th data-sortable="{{ field.sortable }}">
                    {{ field.label }}
                    {% if field.sortable %}
                    <span class="sort-icon">⇅</span>
                    {% endif %}
                </th>
                {% endfor %}
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            {% if objects %}
                {% for obj in objects %}
                <tr data-id="{{ obj.id }}">
                    <td><input type="checkbox" class="row-select" value="{{ obj.id }}"></td>
                    {% for field in fields %}
                    <td>{{ obj[field.name]|default:"—" }}</td>
                    {% endfor %}
                    <td class="actions-cell">
                        <button class="btn btn-sm btn-info" onclick="viewRecord({{ obj.id }})">View</button>
                        <button class="btn btn-sm btn-primary" onclick="editRecord({{ obj.id }})">Edit</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteRecord({{ obj.id }})">Delete</button>
                    </td>
                </tr>
                {% endfor %}
            {% else %}
                <tr>
                    <td colspan="{{ fields|length + 2 }}" class="empty-state">
                        No records found. <a href="/admin/{{ model_name }}/create">Create one now</a>
                    </td>
                </tr>
            {% endif %}
        </tbody>
    </table>
</div>

{% if pagination %}
<div class="pagination">
    {% if pagination.has_previous %}
    <button class="btn btn-sm" onclick="goToPage({{ pagination.previous_page }})">Previous</button>
    {% endif %}
    
    <span class="page-info">
        Page {{ pagination.current_page }} of {{ pagination.total_pages }}
    </span>
    
    {% if pagination.has_next %}
    <button class="btn btn-sm" onclick="goToPage({{ pagination.next_page }})">Next</button>
    {% endif %}
</div>
{% endif %}

<div class="bulk-actions">
    <select id="bulkAction" class="form-control">
        <option value="">Bulk Actions</option>
        <option value="delete">Delete Selected</option>
        <option value="export">Export Selected</option>
    </select>
    <button class="btn btn-primary" onclick="applyBulkAction()">Apply</button>
</div>
{% endblock %}

{% block extra_js %}
<script>
const modelName = "{{ model_name }}";

function viewRecord(id) {
    window.location.href = `/admin/${modelName}/${id}`;
}

function editRecord(id) {
    window.location.href = `/admin/${modelName}/${id}/edit`;
}

async function deleteRecord(id) {
    if (!confirm('Are you sure you want to delete this record?')) return;
    
    try {
        const response = await fetch(`/admin/${modelName}/${id}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        if (response.ok) {
            window.location.reload();
        } else {
            alert('Failed to delete record');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('An error occurred');
    }
}

function exportData() {
    window.location.href = `/admin/${modelName}/export`;
}

function applyFilters() {
    const searchTerm = document.getElementById('searchInput').value;
    const url = new URL(window.location);
    url.searchParams.set('search', searchTerm);
    window.location.href = url.toString();
}

function clearFilters() {
    window.location.href = `/admin/${modelName}`;
}

function goToPage(page) {
    const url = new URL(window.location);
    url.searchParams.set('page', page);
    window.location.href = url.toString();
}

function applyBulkAction() {
    const action = document.getElementById('bulkAction').value;
    if (!action) {
        alert('Please select an action');
        return;
    }
    
    const selected = Array.from(document.querySelectorAll('.row-select:checked'))
        .map(cb => cb.value);
    
    if (selected.length === 0) {
        alert('Please select at least one record');
        return;
    }
    
    if (action === 'delete') {
        if (!confirm(`Are you sure you want to delete ${selected.length} record(s)?`)) return;
        
        fetch(`/admin/${modelName}/bulk-delete`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ ids: selected })
        })
        .then(response => {
            if (response.ok) {
                window.location.reload();
            } else {
                alert('Failed to delete records');
            }
        });
    } else if (action === 'export') {
        window.location.href = `/admin/${modelName}/export?ids=${selected.join(',')}`;
    }
}

// Select all checkbox
document.getElementById('selectAll').addEventListener('change', function() {
    const checkboxes = document.querySelectorAll('.row-select');
    checkboxes.forEach(cb => cb.checked = this.checked);
});
</script>
{% endblock %}
