@props([
    'pageTitle' => '',
    'data' => [],
    'columns' => [],
    'actions' => [],
    'showAddButton' => false,
    'addButtonUrl' => '#',
    'currentPage' => 1,
    'lastPage' => 1,
    'total' => 0,
])

<div class="card-header border-0 bg-transparent">
    <div class="d-flex justify-content-between align-items-center">
        <h5 class="mb-0 fw-bold text-dark">{{ $pageTitle }}</h5>
        @if ($showAddButton)
            <a href="{{ $addButtonUrl }}" class="btn btn-primary btn-sm px-3">
                <i class="fa-solid fa-plus me-1"></i> Add {{ $pageTitle }}
            </a>
        @endif
    </div>
</div>
<div class="card-body">
    <!-- Search -->
    <div class="row mb-3">
        <div class="col-12 col-md-6">
            <div class="input-group input-group-sm">
                <span class="input-group-text bg-light border-end-0">
                    <i class="fa-solid fa-magnifying-glass text-muted"></i>
                </span>
                <input type="text" class="form-control border-start-0" placeholder="Search..." id="searchInput">
            </div>
        </div>
    </div>

    <!-- Table -->
    <div class="table-container">
        <table class="table table-hover align-middle">
            <thead class="table-light">
                <tr>
                    @foreach ($columns as $index => $column)
                        <th class="{{ $column['sortable'] ? 'sortable' : '' }}" data-column="{{ $index }}">
                            {{ $column['name'] }}
                            @if ($column['sortable'])
                                <i class="fa-solid fa-sort"></i>
                            @endif
                        </th>
                    @endforeach
                    @if (!empty($actions))
                        <th class="text-center" style="width: 120px;">Action</th>
                    @endif
                </tr>
            </thead>
            <tbody id="tableBody"></tbody>
        </table>
    </div>

    <!-- Pagination -->
    <div class="d-flex justify-content-end mt-4">
        <nav aria-label="Page navigation">
            <ul class="pagination pagination-sm" id="pagination"></ul>
        </nav>
    </div>
</div>

<style>
    .table-container { overflow-x: auto; }
    .table th, .table td { white-space: nowrap; }
    .sortable { cursor: pointer; }
    .sortable:hover { background-color: #f8f9fa; }
    .sortable i { margin-left: 5px; color: #6c757d; }
    .view-btn { border-color: #0d6efd; color: #0d6efd; }
    .view-btn:hover { background-color: #0d6efd; color: #fff; }
    .edit-btn { border-color: #ffc107; color: #ffc107; }
    .edit-btn:hover { background-color: #ffc107; color: #fff; }
    .delete-btn { border-color: #dc3545; color: #dc3545; }
    .delete-btn:hover { background-color: #dc3545; color: #fff; }
</style>

<script>
    const tableConfig = {
        data: @json($data),
        columns: @json($columns),
        actions: @json($actions),
        pageTitle: @json($pageTitle),
        csrfToken: '{{ csrf_token() }}',
        currentPage: {{ $currentPage }},
        lastPage: {{ $lastPage }},
        total: {{ $total }},
    };

    const rowsPerPage = 5;
    let currentPage = tableConfig.currentPage;
    let filteredRows = [...tableConfig.data];

    function renderTable() {
        const tableBody = document.getElementById('tableBody');
        tableBody.innerHTML = '';

        const startIndex = (currentPage - 1) * rowsPerPage;
        const endIndex = startIndex + rowsPerPage;
        const paginatedRows = filteredRows.slice(startIndex, endIndex);

        paginatedRows.forEach(row => {
            let rowHtml = `<tr>`;
            tableConfig.columns.forEach(col => {
                rowHtml += `<td>${row[col.key] || ''}</td>`;
            });
            if (tableConfig.actions.length > 0) {
                rowHtml += `<td class="text-center">`;
                const routeBase = tableConfig.pageTitle.toLowerCase().replace(/\s+/g, '-');
                tableConfig.actions.forEach(action => {
                    if (action === 'view') {
                        rowHtml += `<a href="/${routeBase}/${row.id}" class="btn btn-sm view-btn me-1" title="View"><i class="fa-solid fa-eye"></i></a>`;
                    } else if (action === 'edit') {
                        rowHtml += `<a href="/${routeBase}/${row.id}/edit" class="btn btn-sm edit-btn me-1" title="Edit"><i class="fa-solid fa-pen"></i></a>`;
                    } else if (action === 'delete') {
                        rowHtml += `<a href="/${routeBase}/${row.id}" class="btn btn-sm delete-btn" title="Delete" onclick="event.preventDefault(); if(confirm('Are you sure you want to delete this ${tableConfig.pageTitle.toLowerCase()}?')) { document.getElementById('delete-form-${row.id}').submit(); }"><i class="fa-solid fa-trash"></i></a>
                                    <form id="delete-form-${row.id}" action="/${routeBase}/${row.id}" method="POST" style="display: none;">
                                        @csrf
                                        @method('DELETE')
                                    </form>`;
                    }
                });
                rowHtml += `</td>`;
            }
            rowHtml += `</tr>`;
            tableBody.innerHTML += rowHtml;
        });
    }

    function renderPagination() {
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = '';

        const totalPages = Math.ceil(filteredRows.length / rowsPerPage);
        const routeBase = tableConfig.pageTitle.toLowerCase().replace(/\s+/g, '-');

        pagination.innerHTML += `<li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="/${routeBase}?page=${currentPage - 1}" aria-label="Previous">«</a>
        </li>`;
        for (let i = 1; i <= totalPages; i++) {
            pagination.innerHTML += `<li class="page-item ${currentPage === i ? 'active' : ''}">
                <a class="page-link" href="/${routeBase}?page=${i}">${i}</a>
            </li>`;
        }
        pagination.innerHTML += `<li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="/${routeBase}?page=${currentPage + 1}" aria-label="Next">»</a>
        </li>`;
    }

    document.getElementById('searchInput')?.addEventListener('input', function() {
        const searchTerm = this.value.toLowerCase();
        filteredRows = tableConfig.data.filter(row =>
            Object.values(row).some(value =>
                value && value.toString().toLowerCase().includes(searchTerm)
            )
        );
        currentPage = 1;
        renderTable();
        renderPagination();
    });

    renderTable();
    renderPagination();
</script>