import { getSpinner, getCsrfToken } from '../../utils/helpers.js';

let $tableContainer;
let currentClubId   = null;
let currentEventId  = null;
let currentStatus   = 'PENDING';
let pendingRejectId = null;

export function initApplicationsSection($container) {
    // Build filter + tabs + table wrapper
    $container.html(`
        <div class="apps-filter-bar">
            <select id="apps-club-filter" class="form-select rounded-3">
                <option value="">Все клубы</option>
            </select>
            <select id="apps-event-filter" class="form-select rounded-3">
                <option value="">Все мероприятия</option>
            </select>
        </div>
        <div class="apps-tabs" id="apps-status-tabs">
            <button class="apps-tab active" data-status="PENDING">
                На рассмотрении <span class="apps-tab-count" id="cnt-PENDING">—</span>
            </button>
            <button class="apps-tab" data-status="APPROVED">
                Одобренные <span class="apps-tab-count" id="cnt-APPROVED">—</span>
            </button>
            <button class="apps-tab" data-status="REJECTED">
                Отклонённые <span class="apps-tab-count" id="cnt-REJECTED">—</span>
            </button>
        </div>
        <div id="apps-table-container"></div>
    `);

    $tableContainer = $('#apps-table-container');

    // Wire filters
    $('#apps-club-filter').on('change', function () {
        currentClubId  = $(this).val() || null;
        currentEventId = null;
        $('#apps-event-filter').val('');
        loadEventsFilter(currentClubId, null);
        refreshAll();
    });

    $('#apps-event-filter').on('change', function () {
        currentEventId = $(this).val() || null;
        refreshAll();
    });

    // Wire status tabs
    $('#apps-status-tabs').on('click', '.apps-tab', function () {
        $('#apps-status-tabs .apps-tab').removeClass('active');
        $(this).addClass('active');
        currentStatus = $(this).data('status');
        loadApplications(0);
    });

    // Setup reject modal
    if (!$('#reject-reason-modal').length) {
        $('body').append(buildRejectModal());
        setupRejectModal();
    }

    loadClubsFilter();
    refreshAll();
}

export function filterApplicationsByEvent(eventId, clubId) {
    currentEventId = eventId;
    currentClubId  = clubId || null;
    currentStatus  = 'PENDING';

    // Reset tab active state
    $('#apps-status-tabs .apps-tab').removeClass('active');
    $('#apps-status-tabs .apps-tab[data-status="PENDING"]').addClass('active');

    if (currentClubId) {
        $('#apps-club-filter').val(currentClubId);
        loadEventsFilter(currentClubId, eventId);
    }

    refreshAll();

    const el = document.getElementById('applications-section');
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

// ════════════════════════════════════════════════════════
// FILTERS
// ════════════════════════════════════════════════════════

function loadClubsFilter() {
    $.ajax({
        url: '/api/admin/clubs', type: 'GET',
        success: clubs => {
            const $sel = $('#apps-club-filter');
            $sel.find('option:not(:first)').remove();
            clubs.forEach(c => $sel.append(`<option value="${c.id}">${c.name}</option>`));
            if (currentClubId) {
                $sel.val(currentClubId);
                loadEventsFilter(currentClubId, currentEventId);
            }
        }
    });
}

function loadEventsFilter(clubId, selectedEventId) {
    const $sel = $('#apps-event-filter');
    $sel.find('option:not(:first)').remove();
    $sel.val('');
    if (!clubId) return;

    $.ajax({
        url: `/api/admin/events/by-club/${clubId}`, type: 'GET',
        success: events => {
            events.forEach(e => {
                const dateStr = e.startDateTime ? formatEventDate(e.startDateTime) : '';
                const label   = dateStr ? `${e.title} · ${dateStr}` : e.title;
                const sel     = selectedEventId && e.id === selectedEventId ? 'selected' : '';
                $sel.append(`<option value="${e.id}" ${sel}>${label}</option>`);
            });
            if (selectedEventId) $sel.val(selectedEventId);
        }
    });
}

function formatEventDate(dt) {
    if (!dt) return '';
    try {
        const d = new Date(dt);
        return d.toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit', year: 'numeric' });
    } catch { return ''; }
}

// ════════════════════════════════════════════════════════
// LOAD
// ════════════════════════════════════════════════════════

function refreshAll() {
    loadCounts();
    loadApplications(0);
}

function loadCounts() {
    const params = new URLSearchParams();
    if (currentEventId) params.set('eventId', currentEventId);
    else if (currentClubId) params.set('clubId', currentClubId);

    $.ajax({
        url: `/api/admin/applications/counts?${params}`, type: 'GET',
        success: counts => {
            ['PENDING', 'APPROVED', 'REJECTED'].forEach(s => {
                const n = counts[s] ?? 0;
                $(`#cnt-${s}`).text(n > 0 ? n : '');
            });
        }
    });
}

function loadApplications(page) {
    if (!$tableContainer) return;
    $tableContainer.html(getSpinner());

    const params = new URLSearchParams({ page, size: 20, status: currentStatus });
    if (currentEventId) params.set('eventId', currentEventId);
    else if (currentClubId) params.set('clubId', currentClubId);

    $.ajax({
        url: `/api/admin/applications?${params}`, type: 'GET',
        success: resp => {
            $tableContainer.empty();
            if (!resp.content || resp.content.length === 0) {
                $tableContainer.html(buildEmpty());
                return;
            }
            $tableContainer.append(buildTable(resp.content));
            if (resp.totalPages > 1) {
                $tableContainer.append(buildPager(resp, page));
            }
        },
        error: () => $tableContainer.html('<div class="alert alert-danger">Ошибка загрузки заявок</div>')
    });
}

// ════════════════════════════════════════════════════════
// RENDER
// ════════════════════════════════════════════════════════

function buildTable(apps) {
    const isPending  = currentStatus === 'PENDING';
    const isRejected = currentStatus === 'REJECTED';

    const actionsTh = isPending ? '<th>Действия</th>' : '';

    const rows = apps.map(a => {
        const actionsTd = isPending
            ? `<td>
                <div class="d-flex gap-1">
                    <button class="btn btn-sm apps-action-approve" data-id="${a.id}" title="Одобрить">
                        <i class="bi bi-check-lg"></i> Принять
                    </button>
                    <button class="btn btn-sm apps-action-reject" data-id="${a.id}" title="Отклонить">
                        <i class="bi bi-x-lg"></i> Отклонить
                    </button>
                </div>
               </td>`
            : '';

        const rejectionRow = isRejected && a.rejectionReason
            ? `<div class="apps-rejection-note"><i class="bi bi-info-circle me-1"></i>${esc(a.rejectionReason)}</div>`
            : '';

        return `
            <tr data-app-id="${a.id}">
                <td>
                    <div class="fw-semibold">${esc(a.fullName)}</div>
                    <div class="text-muted small">${esc(a.email)}</div>
                    ${rejectionRow}
                </td>
                <td class="text-muted small">${a.phone ? esc(a.phone) : '—'}</td>
                <td class="text-muted small">${a.birthDate ? formatLocalDate(a.birthDate) : '—'}</td>
                <td class="text-muted small">${a.gender ? esc(a.gender) : '—'}</td>
                <td class="text-muted small">${a.ratingPoints != null ? a.ratingPoints : '—'}</td>
                <td><span class="apps-badge apps-badge-${a.status}">${statusLabel(a.status)}</span></td>
                <td>
                    <div class="fw-semibold small">${esc(a.eventTitle || '')}</div>
                    <div class="text-muted small">${esc(a.clubName || '')}</div>
                </td>
                <td class="text-muted small">${formatDateTime(a.createdAt)}</td>
                ${actionsTd}
            </tr>`;
    }).join('');

    const $wrap = $(`
        <div class="table-responsive">
            <table class="apps-table">
                <thead>
                    <tr>
                        <th>Участник</th>
                        <th>Телефон</th>
                        <th>Дата рожд.</th>
                        <th>Пол</th>
                        <th>Очки</th>
                        <th>Статус</th>
                        <th>Мероприятие</th>
                        <th>Подано</th>
                        ${actionsTh}
                    </tr>
                </thead>
                <tbody>${rows}</tbody>
            </table>
        </div>`);

    // Wire action buttons
    $wrap.on('click', '.apps-action-approve', function () {
        const id = $(this).data('id');
        submitApprove(id, $(this).closest('tr'));
    });
    $wrap.on('click', '.apps-action-reject', function () {
        pendingRejectId = $(this).data('id');
        $('#reject-reason-text').val('');
        bootstrap.Modal.getOrCreateInstance(document.getElementById('reject-reason-modal')).show();
    });

    return $wrap;
}

function buildEmpty() {
    const label = { PENDING: 'ожидающих рассмотрения', APPROVED: 'одобренных', REJECTED: 'отклонённых' }[currentStatus] || '';
    return `<div class="text-center py-5 text-muted">
        <i class="bi bi-inbox fs-1 d-block mb-3 opacity-50"></i>
        <h5 class="fw-semibold">Нет ${label} заявок</h5>
    </div>`;
}

function buildPager(resp, currentPage) {
    const $pag = $('<div class="d-flex justify-content-center gap-1 mt-3 flex-wrap"></div>');
    for (let i = 0; i < resp.totalPages; i++) {
        const $btn = $(`<button class="btn btn-sm ${i === currentPage ? 'btn-secondary' : 'btn-outline-secondary'}"
                                style="min-width:36px">${i + 1}</button>`);
        if (i !== currentPage) $btn.on('click', () => loadApplications(i));
        $pag.append($btn);
    }
    return $pag;
}

// ════════════════════════════════════════════════════════
// ACTIONS
// ════════════════════════════════════════════════════════

function submitApprove(appId, $row) {
    $row.find('.apps-action-approve,.apps-action-reject').prop('disabled', true);

    $.ajax({
        url:  `/api/admin/applications/${appId}/approve`,
        type: 'PATCH',
        beforeSend: xhr => xhr.setRequestHeader('X-XSRF-TOKEN', getCsrfToken()),
        success: () => {
            $row.addClass('apps-row-success');
            $row.find('.apps-badge').attr('class', 'apps-badge apps-badge-APPROVED').text(statusLabel('APPROVED'));
            $row.find('.apps-action-approve,.apps-action-reject').remove();
            loadCounts();
        },
        error: () => {
            $row.find('.apps-action-approve,.apps-action-reject').prop('disabled', false);
            alert('Ошибка при одобрении заявки');
        }
    });
}

// ════════════════════════════════════════════════════════
// REJECT MODAL
// ════════════════════════════════════════════════════════

function buildRejectModal() {
    return `
    <div class="modal fade" id="reject-reason-modal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered" style="max-width:460px">
            <div class="modal-content border-0 rounded-4 overflow-hidden" style="box-shadow:0 20px 60px rgba(0,0,0,0.18)">
                <div style="background:linear-gradient(135deg,#c0392b,#e74c3c);padding:18px 24px;display:flex;align-items:center;justify-content:space-between">
                    <div class="d-flex align-items-center gap-2">
                        <div style="width:36px;height:36px;border-radius:8px;background:rgba(255,255,255,0.2);display:flex;align-items:center;justify-content:center;color:#fff;font-size:1rem">
                            <i class="bi bi-x-circle"></i>
                        </div>
                        <h5 class="modal-title mb-0 text-white fw-bold">Отклонить заявку</h5>
                    </div>
                    <button type="button" class="btn-close btn-close-white opacity-75" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4">
                    <p class="text-muted small mb-3">Участник получит письмо об отклонении. Укажите причину (необязательно).</p>
                    <div class="form-floating">
                        <textarea class="form-control rounded-3" id="reject-reason-text"
                                  placeholder=" " style="height:100px"></textarea>
                        <label for="reject-reason-text">Причина отказа</label>
                    </div>
                </div>
                <div class="modal-footer border-0 px-4 pb-4 pt-0 gap-2">
                    <button type="button" class="btn btn-light fw-semibold px-4 rounded-3"
                            data-bs-dismiss="modal">Отмена</button>
                    <button type="button" class="btn fw-semibold px-4 rounded-3" id="reject-confirm-btn"
                            style="background:#e74c3c;color:#fff;border:none">
                        <i class="bi bi-x-circle me-1"></i>Отклонить
                    </button>
                </div>
            </div>
        </div>
    </div>`;
}

function setupRejectModal() {
    $('#reject-confirm-btn').on('click', function () {
        if (!pendingRejectId) return;
        const $btn = $(this);
        const orig = $btn.html();
        $btn.html('<span class="spinner-border spinner-border-sm me-1"></span>Отклонение...').prop('disabled', true);

        const reason = $('#reject-reason-text').val().trim();
        const idToReject = pendingRejectId;
        pendingRejectId = null;

        $.ajax({
            url:         `/api/admin/applications/${idToReject}/reject`,
            type:        'PATCH',
            contentType: 'application/json',
            data:        JSON.stringify({ reason }),
            beforeSend:  xhr => xhr.setRequestHeader('X-XSRF-TOKEN', getCsrfToken()),
            success: () => {
                bootstrap.Modal.getInstance(document.getElementById('reject-reason-modal'))?.hide();
                loadApplications(0);
                loadCounts();
            },
            error: () => {
                alert('Ошибка при отклонении заявки');
                $btn.html(orig).prop('disabled', false);
            }
        });
    });

    $('#reject-reason-modal').on('hidden.bs.modal', () => {
        pendingRejectId = null;
        const $btn = $('#reject-confirm-btn');
        $btn.html('<i class="bi bi-x-circle me-1"></i>Отклонить').prop('disabled', false);
    });
}

// ════════════════════════════════════════════════════════
// HELPERS
// ════════════════════════════════════════════════════════

function statusLabel(status) {
    return { PENDING: 'На рассмотрении', APPROVED: 'Одобрено', REJECTED: 'Отклонено' }[status] || status;
}

function formatLocalDate(dateVal) {
    if (!dateVal) return '—';
    // R2DBC may return array [y, m, d] or ISO string
    if (Array.isArray(dateVal)) {
        const [y, m, d] = dateVal;
        return `${String(d).padStart(2,'0')}.${String(m).padStart(2,'0')}.${y}`;
    }
    const parts = String(dateVal).split('-');
    if (parts.length === 3) return `${parts[2]}.${parts[1]}.${parts[0]}`;
    return dateVal;
}

function formatDateTime(dt) {
    if (!dt) return '—';
    try {
        const d = new Date(dt);
        if (isNaN(d)) return dt;
        return d.toLocaleString('ru-RU', { day:'2-digit', month:'2-digit', year:'numeric',
            hour:'2-digit', minute:'2-digit' });
    } catch { return dt; }
}

function esc(str) {
    if (!str) return '';
    return String(str)
        .replace(/&/g, '&amp;').replace(/</g, '&lt;')
        .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
