import { getSpinner, formatDate, formatTime, buildPagination, eventTypeLabel, getCsrfToken } from '../../utils/helpers.js';
import { createImageUploader } from '../../utils/imageUploader.js';
import { getCachedClubs } from './clubsSection.js';
import { filterApplicationsByEvent } from './applicationsSection.js';

let $globalContainer;
let globalOnStats;
let editingEventId  = null;
let eventUploader   = null;

export function initAdminEvents($container, onStats) {
    $globalContainer = $container;
    globalOnStats    = onStats;

    if (!$('#create-event-modal').length) {
        $('body').append(buildEventModal());
        setupEventModal();
    }

    loadEvents($container, onStats, 0);
}

// ════════════════════════════════════════════════════════
// ЗАГРУЗКА И РЕНДЕР
// ════════════════════════════════════════════════════════

function loadEvents($container, onStats, page) {
    $container.html(getSpinner());

    $.ajax({
        url: `/api/admin/events?page=${page}&size=10`,
        type: 'GET',
        success: (resp) => {
            $container.empty();

            if (!resp.content || resp.content.length === 0) {
                $container.append(buildEmpty());
                onStats({ events: 0, active: 0 });
                return;
            }

            const $grid = $('<div class="row g-3"></div>');
            resp.content.forEach(event => {
                const $col = $('<div class="col-12 col-md-6 col-xl-4"></div>').append(buildEventCard(event));
                $grid.append($col);
            });
            onStats({ events: resp.totalElements, active: resp.content.length });
            $container.append($grid);

            const $pag = buildPagination(resp, page, p => loadEvents($container, onStats, p));
            if ($pag) $container.append($pag);
        },
        error: () => $container.html('<div class="alert alert-danger">Ошибка загрузки мероприятий</div>')
    });
}

function buildEventCard(event) {
    const badgeClass = {
        TOURNAMENT: 'bg-danger',
        TRAINING:   'bg-success',
        LESSON:     'bg-primary',
        EXHIBITION: 'bg-warning text-dark',
        CAMP:       'bg-info text-dark'
    }[event.type] || 'bg-secondary';

    const $card = $(`
        <div class="event-card" data-event-id="${event.id}">
            <div class="card-img-wrap">
                ${event.imageUrl
                    ? `<img src="${event.imageUrl}" alt="${event.title}">`
                    : `<div class="card-img-placeholder"><i class="bi bi-calendar-event"></i></div>`}
            </div>
            <div class="d-flex align-items-start justify-content-between mb-1 gap-2">
                <div class="event-title mb-0">${event.title}</div>
                <div class="d-flex gap-1 flex-shrink-0 mt-1">
                    ${event.registrationOpen === false
                        ? '<span class="badge bg-secondary">Набор закрыт</span>'
                        : ''}
                    <span class="badge ${badgeClass}">${eventTypeLabel(event.type)}</span>
                </div>
            </div>
            <div class="event-info">
                <div class="info-item"><i class="bi bi-building"></i>${event.clubName || 'Клуб не указан'}</div>
                <div class="info-item"><i class="bi bi-calendar"></i>${formatDate(event.startDateTime)}</div>
                <div class="info-item"><i class="bi bi-clock"></i>${formatTime(event.startDateTime)}</div>
                ${event.takePartPrice != null
                    ? `<div class="info-item"><i class="bi bi-currency-rouble"></i>${event.takePartPrice > 0 ? event.takePartPrice + ' ₽' : 'Бесплатно'}</div>`
                    : ''}
            </div>
            ${event.description ? `<p class="text-muted small mb-2">${event.description}</p>` : ''}
            ${event.maxParticipants ? `
                <div class="small text-muted mb-2">
                    <i class="bi bi-people me-1"></i>${event.currentParticipants || 0} / ${event.maxParticipants} участников
                </div>` : ''}
            <div class="d-flex gap-2 flex-wrap">
                <button class="btn-admin btn-sm edit-event-btn">
                    <i class="bi bi-pencil me-1"></i>Редактировать
                </button>
                <button class="btn btn-sm fw-semibold applications-btn"
                        style="background:#3498db;color:#fff;border:none;border-radius:8px;padding:6px 14px">
                    <i class="bi bi-people me-1"></i>Заявки
                </button>
                <button class="btn btn-sm fw-semibold toggle-reg-btn"
                        style="background:${event.registrationOpen !== false ? '#f39c12' : '#27ae60'};color:#fff;border:none;border-radius:8px;padding:6px 14px">
                    <i class="bi bi-${event.registrationOpen !== false ? 'lock' : 'unlock'} me-1"></i>${event.registrationOpen !== false ? 'Закрыть нвбор' : 'Открыть набор'}
                </button>
            </div>
        </div>
    `);

    $card.on('click', '.edit-event-btn', () => openEventModal(event));
    $card.on('click', '.applications-btn', () => filterApplicationsByEvent(event.id, event.clubUuid));
    $card.on('click', '.toggle-reg-btn', function () {
        const $btn = $(this);
        $btn.prop('disabled', true);
        $.ajax({
            url:  `/api/admin/events/${event.id}/toggle-registration`,
            type: 'PATCH',
            beforeSend: xhr => xhr.setRequestHeader('X-XSRF-TOKEN', getCsrfToken()),
            success: (resp) => {
                const open = resp.registrationOpen;
                event.registrationOpen = open;
                $btn.css('background', open ? '#f39c12' : '#27ae60')
                    .html(`<i class="bi bi-${open ? 'lock' : 'unlock'} me-1"></i>${open ? 'Закрыть набор' : 'Открыть набор'}`)
                    .prop('disabled', false);
                $card.find('.badge.bg-secondary').remove();
                if (!open) {
                    $card.find('.d-flex.gap-1.flex-shrink-0').prepend('<span class="badge bg-secondary">Набор закрыт</span>');
                }
            },
            error: () => { alert('Ошибка'); $btn.prop('disabled', false); }
        });
    });
    return $card;
}

function buildEmpty() {
    return `<div class="text-center py-5 text-muted">
        <i class="bi bi-calendar-event fs-1 d-block mb-3 text-secondary opacity-50"></i>
        <h5 class="fw-semibold">Мероприятий пока нет</h5>
        <p>Создайте первое мероприятие для ваших клубов</p>
        <button class="btn-admin px-4 fs-5" data-bs-toggle="modal" data-bs-target="#create-event-modal">
            <i class="bi bi-plus-circle me-1"></i>Создать мероприятие
        </button>
    </div>`;
}

// ════════════════════════════════════════════════════════
// МОДАЛ МЕРОПРИЯТИЯ
// ════════════════════════════════════════════════════════

function buildEventModal() {
    const typeOptions = [
        { value: 'TOURNAMENT', label: 'Турнир' },
        { value: 'TRAINING',   label: 'Тренировка' },
        { value: 'LESSON',     label: 'Урок' },
        { value: 'EXHIBITION', label: 'Выставочный' },
        { value: 'CAMP',       label: 'Лагерь' }
    ].map(t => `<option value="${t.value}">${t.label}</option>`).join('');

    return `
    <div class="modal fade" id="create-event-modal" tabindex="-1" data-bs-backdrop="static">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content border-0 rounded-4 overflow-hidden shadow-xl">

                <div class="modal-header-dark">
                    <div class="d-flex align-items-center gap-2">
                        <div class="modal-header-icon">
                            <i class="bi bi-calendar-plus"></i>
                        </div>
                        <h5 class="modal-title mb-0" id="event-modal-title">Создать мероприятие</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" style="max-height:72vh;overflow-y:auto">

                    <p class="modal-section-label">Изображение</p>
                    <div id="event-image-zone" class="mb-4"></div>

                    <p class="modal-section-label">О мероприятии</p>
                    <div class="row g-3 mb-4">
                        <div class="col-md-8">
                            <div class="form-floating">
                                <input type="text" class="form-control rounded-3" id="event-title" placeholder=" ">
                                <label for="event-title">Название <span class="text-danger">*</span></label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-floating">
                                <select class="form-select rounded-3" id="event-type">${typeOptions}</select>
                                <label for="event-type">Тип</label>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-floating">
                                <select class="form-select rounded-3" id="event-club"></select>
                                <label for="event-club">Клуб <span class="text-danger">*</span></label>
                            </div>
                        </div>
                    </div>

                    <p class="modal-section-label">Расписание</p>
                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <div class="form-floating">
                                <input type="datetime-local" class="form-control rounded-3" id="event-start" placeholder=" ">
                                <label for="event-start"><i class="bi bi-play-circle me-1"></i>Начало</label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-floating">
                                <input type="datetime-local" class="form-control rounded-3" id="event-end" placeholder=" ">
                                <label for="event-end"><i class="bi bi-stop-circle me-1"></i>Конец</label>
                            </div>
                        </div>
                    </div>

                    <p class="modal-section-label">Участие</p>
                    <div class="row g-3 mb-4">
                        <div class="col-md-4">
                            <div class="form-floating">
                                <input type="number" class="form-control rounded-3" id="event-max-participants"
                                       placeholder=" " min="1">
                                <label for="event-max-participants"><i class="bi bi-people me-1"></i>Макс. участников</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-floating">
                                <input type="number" class="form-control rounded-3" id="event-price"
                                       placeholder=" " min="0" step="0.01">
                                <label for="event-price"><i class="bi bi-currency-rouble me-1"></i>Цена (₽)</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-floating">
                                <input type="text" class="form-control rounded-3" id="event-phone" placeholder=" ">
                                <label for="event-phone"><i class="bi bi-telephone me-1"></i>Телефон</label>
                            </div>
                        </div>
                    </div>

                    <p class="modal-section-label">Описание</p>
                    <div class="row g-3">
                        <div class="col-12">
                            <div class="form-floating">
                                <textarea class="form-control rounded-3" id="event-description"
                                          placeholder=" " style="height:80px"></textarea>
                                <label for="event-description">Описание мероприятия</label>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-floating">
                                <textarea class="form-control rounded-3" id="event-requirements"
                                          placeholder=" " style="height:70px"></textarea>
                                <label for="event-requirements">Требования к участникам</label>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="modal-footer border-0 px-4 pb-4 pt-2 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-admin rounded-3 px-4" id="save-event-btn">
                        <i class="bi bi-check-lg me-1"></i><span id="save-event-label">Создать мероприятие</span>
                    </button>
                </div>
            </div>
        </div>
    </div>`;
}

function setupEventModal() {
    eventUploader = createImageUploader($('#event-image-zone'), '/api/admin/upload/image');

    $('#create-event-modal').on('show.bs.modal', (e) => {
        if (!e.relatedTarget && editingEventId === null) {
            clearEventForm();
        }
        populateClubsSelect(null);
        $('#save-event-btn').off('click.save').on('click.save', saveEvent);
    });
}

function openEventModal(event = null) {
    editingEventId = event ? event.id : null;

    if (event) {
        $('#event-modal-title').text('Редактировать мероприятие');
        $('#save-event-label').text('Сохранить');
        $('#event-title').val(event.title || '');
        $('#event-type').val(event.type || 'TOURNAMENT');
        $('#event-start').val(event.startDateTime ? event.startDateTime.slice(0, 16) : '');
        $('#event-end').val(event.endDateTime     ? event.endDateTime.slice(0, 16)   : '');
        $('#event-max-participants').val(event.maxParticipants || '');
        $('#event-price').val(event.takePartPrice ?? '');
        $('#event-phone').val(event.contactPhone || '');
        $('#event-description').val(event.description || '');
        $('#event-requirements').val(event.requirements || '');
        eventUploader && eventUploader.setUrl(event.imageUrl || null);
        populateClubsSelect(event.clubUuid);
    } else {
        clearEventForm();
        populateClubsSelect(null);
    }

    bootstrap.Modal.getOrCreateInstance(document.getElementById('create-event-modal')).show();
}

function clearEventForm() {
    editingEventId = null;
    $('#event-modal-title').text('Создать мероприятие');
    $('#save-event-label').text('Создать мероприятие');
    $('#event-title,#event-description,#event-requirements,#event-phone').val('');
    $('#event-start,#event-end').val('');
    $('#event-max-participants,#event-price').val('');
    eventUploader && eventUploader.reset();
}

function populateClubsSelect(selectedUuid) {
    const clubs = getCachedClubs();
    const $select = $('#event-club').empty();
    if (clubs.length === 0) {
        $select.append('<option value="">Сначала создайте клуб</option>');
    } else {
        $select.append('<option value="">— Выберите клуб —</option>');
        clubs.forEach(c => {
            const selected = selectedUuid && c.id === selectedUuid ? 'selected' : '';
            $select.append(`<option value="${c.id}" ${selected}>${c.name}</option>`);
        });
    }
}

function saveEvent() {
    const title    = $('#event-title').val().trim();
    const clubUuid = $('#event-club').val();
    if (!title)    { alert('Название обязательно'); return; }
    if (!clubUuid) { alert('Выберите клуб'); return; }

    const $btn = $('#save-event-btn');
    const orig = $btn.html();
    $btn.html('<span class="spinner-border spinner-border-sm me-1"></span>Сохранение...').prop('disabled', true);

    const isEdit = editingEventId !== null;
    $.ajax({
        url:         isEdit ? `/api/admin/events/${editingEventId}` : '/api/admin/events',
        type:        isEdit ? 'PUT' : 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            title,
            clubUuid,
            type:            $('#event-type').val(),
            description:     $('#event-description').val().trim()  || null,
            startDateTime:   $('#event-start').val()               || null,
            endDateTime:     $('#event-end').val()                 || null,
            maxParticipants: parseInt($('#event-max-participants').val()) || null,
            takePartPrice:   parseFloat($('#event-price').val())   || null,
            requirements:    $('#event-requirements').val().trim() || null,
            contactPhone:    $('#event-phone').val().trim()        || null,
            imageUrl:        eventUploader ? eventUploader.getUrl() : null
        }),
        beforeSend: xhr => xhr.setRequestHeader('X-XSRF-TOKEN', getCsrfToken()),
        success: () => {
            bootstrap.Modal.getInstance(document.getElementById('create-event-modal')).hide();
            loadEvents($globalContainer, globalOnStats, 0);
        },
        error:    () => alert(isEdit ? 'Ошибка при обновлении мероприятия' : 'Ошибка при создании мероприятия'),
        complete: () => $btn.html(orig).prop('disabled', false)
    });
}
