{% extends 'admin/base.html' %}

{% block title %}Manage Companies{% endblock %}

{% block content %}
<div class="page-header">
    <div>
        <h1 class="page-title">Companies</h1>
        <p class="page-subtitle">
            Review new registrations, approve access, or follow up on pending verifications.
        </p>
    </div>
    
</div>



{% if error %}
    <div class="alert alert-danger" role="alert">
        {{ error }}
    </div>
{% endif %}

<div id="companiesFeedback" class="toast hidden"></div>

<div class="card">
    <div class="card-header">
        <!-- <div>
            <h2 class="card-title">Registered Companies</h2>
            <p class="card-subtitle">Approve, reject, or follow up on each organisation.</p>
        </div> -->
        <!-- <div class="legend">
            <span class="legend-item"><span class="status status-approved"></span> Approved</span>
            <span class="legend-item"><span class="status status-pending"></span> Pending</span>
            <span class="legend-item"><span class="status status-rejected"></span> Rejected</span>
        </div> -->
        <div class="filters-toolbar companies-filters">
            <div class="filter-input">
                <label for="companySearch">Company / Email</label>
                <div class="input-wrapper">
                    <i class="fa-light fa-magnifying-glass"></i>
                    <input type="text" id="companySearch" placeholder="Search company or email">
                </div>
            </div>
            <div class="filter-input">
                <label for="dateFrom">From</label>
                <div class="input-wrapper">
                    <i class="fa-light fa-calendar-day"></i>
                    <input type="date" id="dateFrom">
                </div>
            </div>
            <div class="filter-input">
                <label for="dateTo">To</label>
                <div class="input-wrapper">
                    <i class="fa-light fa-calendar-day"></i>
                    <input type="date" id="dateTo">
                </div>
            </div>
            <div class="filter-input">
                <label for="statusFilter">Status</label>
                <div class="input-wrapper input-select">
                    <i class="fa-light fa-signal-bars"></i>
                    <select id="statusFilter">
                        <option value="all">All statuses</option>
                        <option value="pending">Pending</option>
                        <option value="approved">Approved</option>
                        <option value="rejected">Rejected</option>
                    </select>
                </div>
            </div>
            <div class="filter-action">
                <button id="refreshCompanies" class="btn btn-secondary">
                    <i class="fa-light fa-rotate"></i>
                    <span>Refresh</span>
                </button>
            </div>
        </div>
    </div>
    <div class="card-body">
        {% if companies %}
            <div class="table-responsive">
                <table class="table companies-table">
                    <thead>
                         <tr>
                             <th>Company</th>
                             <th>Email</th>
                             <th>Status</th>
                             <th>Email Verification</th>
                             <th>Created</th>
                             <th class="text-right">Actions</th>
                         </tr>
                    </thead>
                    <tbody>
                        {% for company in companies %}
                            <tr data-company-id="{{ company.id }}" data-status="{{ company.status }}">
                                <td>{{ company.name }}</td>
                                <td>{{ company.email }}</td>
                                <td>
                                    <span class="status status-{{ company.status }}">{{ company.status|capitalize }}</span>
                                </td>
                                <td>
                                    {% if company.is_verified %}
                                        <span class="badge badge-success">Email verified</span>
                                    {% else %}
                                        <span class="badge badge-warning">Awaiting verification</span>
                                    {% endif %}
                                </td>
                                 <td>{{ company.created_at.strftime('%Y-%m-%d %H:%M') if company.created_at else 'N/A' }}</td>
                                <td class="actions text-right">
                                     <div class="action-buttons" data-current-status="{{ company.status }}">
                                         <a class="btn btn-ghost" title="View" href="{{ url_for('admin.company_detail', company_id=company.id) }}">
                                             <i class="fa-light fa-eye"></i>
                                             <!-- <span>View</span> -->
                                         </a>
                                         <button class="btn btn-ghost" title="Mark Pending" data-action="pending">
                                             <i class="fa-light fa-hourglass-half"></i>
                                             <!-- <span>Mark Pending</span> -->
                                         </button>
                                         <button class="btn btn-success" title="Approve" data-action="approved">
                                             <i class="fa-light fa-badge-check"></i>
                                             <!-- <span>Approve</span> -->
                                         </button>
                                         <button class="btn btn-danger" title="Reject" data-action="rejected">
                                             <i class="fa-light fa-circle-xmark"></i>
                                             <!-- <span>Reject</span> -->
                                         </button>
                                     </div>
                                </td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
            <div class="table-footer">
                <div id="companiesCount" class="table-count"></div>
                <div class="pagination-controls" id="companiesPagination">
                    <button type="button" id="companiesPrev" class="btn btn-ghost">Previous</button>
                    <span id="companiesPageLabel">Page 1</span>
                    <button type="button" id="companiesNext" class="btn btn-ghost">Next</button>
                </div>
            </div>
        {% else %}
            <div class="empty-state">
                <i class="fa-light fa-users-slash"></i>
                <p>No companies found. New registrations will appear here.</p>
            </div>
        {% endif %}
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    (function () {
        const tableBody = document.querySelector('.companies-table tbody');
        const feedback = document.getElementById('companiesFeedback');
        const statusFilter = document.getElementById('statusFilter');
        const searchInput = document.getElementById('companySearch');
        const refreshButton = document.getElementById('refreshCompanies');
        const dateFromInput = document.getElementById('dateFrom');
        const dateToInput = document.getElementById('dateTo');
        const prevBtn = document.getElementById('companiesPrev');
        const nextBtn = document.getElementById('companiesNext');
        const pageLabel = document.getElementById('companiesPageLabel');
        const countLabel = document.getElementById('companiesCount');

        const rowsPerPage = 10;
        let currentPage = 1;

        function showFeedback(message, tone = 'success') {
            if (!feedback) return;
            feedback.textContent = message;
            feedback.classList.remove('hidden', 'error');
            if (tone === 'error') {
                feedback.classList.add('error');
            } else {
                feedback.classList.remove('error');
            }
            clearTimeout(feedback._timeout);
            feedback._timeout = setTimeout(() => feedback.classList.add('hidden'), 3500);
        }

        function updateActionButtons(container, status) {
            if (!container) return;
            container.dataset.currentStatus = status;
            container.querySelectorAll('[data-action]').forEach(btn => {
                btn.classList.toggle('hidden', btn.dataset.action === status);
            });
        }

        function updateRowStatus(row, newStatus) {
            row.dataset.status = newStatus;
            const statusSpan = row.querySelector('.status');
            if (statusSpan) {
                statusSpan.className = `status status-${newStatus}`;
                statusSpan.textContent = newStatus.charAt(0).toUpperCase() + newStatus.slice(1);
            }
            const actionContainer = row.querySelector('.action-buttons');
            updateActionButtons(actionContainer, newStatus);
        }

        async function handleStatusChange(button) {
            const row = button.closest('tr');
            if (!row) return;

            const companyId = row.dataset.companyId;
            const newStatus = button.dataset.action;

            button.disabled = true;
            button.classList.add('loading');

            try {
                const response = await fetch(`{{ url_for('admin.update_company_status', company_id='__ID__') }}`.replace('__ID__', companyId), {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ status: newStatus }),
                });

                const result = await response.json();

                if (!response.ok || !result.success) {
                    throw new Error(result.error || 'Failed to update status');
                }

                updateRowStatus(row, newStatus);
                refreshView(false);
                showFeedback('Company status updated successfully.');
            } catch (error) {
                console.error(error);
                showFeedback(error.message || 'Unable to update company status.', 'error');
            } finally {
                button.disabled = false;
                button.classList.remove('loading');
            }
        }

        function getFilteredRows() {
            if (!tableBody) return [];
            const statusValue = statusFilter.value;
            const query = (searchInput.value || '').trim().toLowerCase();

            const rows = Array.from(tableBody.querySelectorAll('tr'));
            return rows.filter(row => {
                const statusMatch = statusValue === 'all' || row.dataset.status === statusValue;
                const text = `${row.children[0]?.textContent || ''} ${row.children[1]?.textContent || ''}`.toLowerCase();
                const searchMatch = !query || text.includes(query);
                let dateMatch = true;

                if (dateFromInput && dateFromInput.value) {
                    const rowDateValue = row.dataset.createdAt;
                    if (rowDateValue) {
                        const rowDate = new Date(rowDateValue);
                        const fromDate = new Date(dateFromInput.value);
                        if (!isNaN(rowDate) && !isNaN(fromDate)) {
                            dateMatch = dateMatch && rowDate >= fromDate;
                        }
                    }
                }

                if (dateToInput && dateToInput.value) {
                    const rowDateValue = row.dataset.createdAt;
                    if (rowDateValue) {
                        const rowDate = new Date(rowDateValue);
                        const toDate = new Date(dateToInput.value);
                        if (!isNaN(rowDate) && !isNaN(toDate)) {
                            const endOfDay = new Date(toDate);
                            endOfDay.setHours(23, 59, 59, 999);
                            dateMatch = dateMatch && rowDate <= endOfDay;
                        }
                    }
                }

                return statusMatch && searchMatch && dateMatch;
            });
        }

        function renderTable() {
            const rows = Array.from(tableBody.querySelectorAll('tr'));
            rows.forEach(row => {
                row.style.display = 'none';
            });

            const filteredRows = getFilteredRows();
            const totalPages = Math.max(1, Math.ceil(filteredRows.length / rowsPerPage));

            if (currentPage > totalPages) currentPage = totalPages;

            const start = (currentPage - 1) * rowsPerPage;
            const end = start + rowsPerPage;
            const pageRows = filteredRows.slice(start, end);
            pageRows.forEach(row => {
                row.style.display = '';
            });

            pageLabel.textContent = `Page ${currentPage} of ${totalPages}`;
            prevBtn.disabled = currentPage === 1;
            nextBtn.disabled = currentPage === totalPages;
            const count = filteredRows.length;
            if (countLabel) {
                countLabel.textContent = `${count} compan${count === 1 ? 'y' : 'ies'} found`;
            }
        }

        function refreshView(resetPage = false) {
            if (resetPage) {
                currentPage = 1;
            }
            renderTable();
        }

        if (tableBody) {
            tableBody.querySelectorAll('tr').forEach(row => {
                const container = row.querySelector('.action-buttons');
                updateActionButtons(container, row.dataset.status);
                const createdCell = row.children[4];
                if (createdCell) {
                    const rawText = createdCell.textContent.trim();
                    const parsed = Date.parse(rawText.replace(/-/g, '/'));
                    if (!isNaN(parsed)) {
                        row.dataset.createdAt = new Date(parsed).toISOString();
                    } else {
                        row.dataset.createdAt = rawText;
                    }
                }
            });

            tableBody.addEventListener('click', (event) => {
                const target = event.target.closest('[data-action]');
                if (target) {
                    handleStatusChange(target);
                }
            });
        }

        statusFilter.addEventListener('change', () => refreshView(true));
        if (searchInput) {
            searchInput.addEventListener('input', () => refreshView(true));
        }

        if (prevBtn && nextBtn) {
            prevBtn.addEventListener('click', () => {
                if (currentPage > 1) {
                    currentPage -= 1;
                    renderTable();
                }
            });
            nextBtn.addEventListener('click', () => {
                const totalFiltered = getFilteredRows();
                const totalPages = Math.max(1, Math.ceil(totalFiltered.length / rowsPerPage));
                if (currentPage < totalPages) {
                    currentPage += 1;
                    renderTable();
                }
            });
        }

        if (dateFromInput) {
            dateFromInput.addEventListener('change', () => refreshView(true));
        }
        if (dateToInput) {
            dateToInput.addEventListener('change', () => refreshView(true));
        }

        refreshView(true);

        refreshButton.addEventListener('click', () => window.location.reload());
    })();
</script>
{% endblock %}

{% block extra_css %}
<style>
    .filters-toolbar {
        display: flex;
        flex-wrap: wrap;
        align-items: flex-end;
        gap: 16px;
        padding: 16px 20px;
        background: #f8fafc;
        border-radius: 16px;
        border: 1px solid rgba(148, 163, 184, 0.18);
    }

    .filters-toolbar .filter-input {
        display: flex;
        flex-direction: column;
        gap: 6px;
        flex: 1 1 200px;
        min-width: 180px;
    }

    .filters-toolbar .filter-input label {
        font-size: 12px;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: #64748b;
        font-weight: 600;
    }

    .filters-toolbar .input-wrapper {
        position: relative;
        display: flex;
        align-items: center;
        background: #ffffff;
        border-radius: 12px;
        border: 1px solid #dbe3ee;
        padding: 10px 14px;
        box-shadow: 0 10px 24px rgba(15, 23, 42, 0.05);
        transition: border 0.2s ease, box-shadow 0.2s ease;
    }

    .filters-toolbar .input-wrapper:focus-within {
        border-color: #2563eb;
        box-shadow: 0 12px 26px rgba(37, 99, 235, 0.18);
    }

    .filters-toolbar .input-wrapper i {
        margin-right: 10px;
        color: #94a3b8;
        font-size: 16px;
    }

    .filters-toolbar .input-wrapper input,
    .filters-toolbar .input-wrapper select {
        flex: 1;
        border: none;
        background: transparent;
        outline: none;
        font-size: 14px;
        color: #0f172a;
    }

    .filters-toolbar .input-wrapper select {
        appearance: none;
        padding-right: 18px;
    }

    .filters-toolbar .input-wrapper.input-select {
        position: relative;
    }

    .filters-toolbar .input-wrapper.input-select::after {
        content: '\f107';
        font-family: "Font Awesome 6 Pro";
        position: absolute;
        right: 12px;
        color: #94a3b8;
        pointer-events: none;
    }

    .filters-toolbar .filter-action {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        margin-left: auto;
        flex: 0 0 auto;
    }

    .filters-toolbar .filter-action .btn {
        height: 44px;
        display: inline-flex;
        align-items: center;
        gap: 6px;
    }

    .table-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 12px;
        margin-top: 16px;
    }

    .table-count {
        font-size: 13px;
        color: #64748b;
    }

    .pagination-controls {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .pagination-controls button {
        border-radius: 8px;
        padding: 8px 14px;
    }

    .pagination-controls span {
        font-size: 13px;
        font-weight: 600;
        color: #1f2937;
    }

    @media (max-width: 768px) {
        .filters-toolbar {
            flex-direction: column;
            align-items: stretch;
        }

        .table-footer {
            flex-direction: column;
            align-items: flex-start;
        }
    }
</style>
{% endblock %}