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

let cachedClubs = [];
let $globalContainer;
let globalOnStats;
let editingClubId  = null;
let clubUploader   = null;

// court modal state
let editingCourtId = null;
let courtClubId    = null;
let courtUploader  = null;

export function getCachedClubs() {
    return cachedClubs;
}

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

    if (!$('#create-club-modal').length) {
        $('body').append(buildClubModal());
        setupClubModal();
    }
    if (!$('#create-court-modal').length) {
        $('body').append(buildCourtModal());
        setupCourtModal();
    }

    loadClubs($container, onStats);
}

// ════════════════════════════════════════════════════════
// CLUBS — LOAD & RENDER
// ════════════════════════════════════════════════════════

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

    $.ajax({
        url: '/api/admin/clubs',
        type: 'GET',
        success: (clubs) => {
            cachedClubs = clubs || [];
            $container.empty();

            if (!clubs || clubs.length === 0) {
                $container.append(buildEmpty());
                onStats({ clubs: 0, courts: 0 });
                return;
            }

            // Render all club cards, then load courts for each
            const $grid = $('<div class="row g-3"></div>');
            let courtTotal = 0;
            let pending = clubs.length;

            clubs.forEach(club => {
                const $card = buildClubCard(club);
                const $col = $('<div class="col-12 col-md-6 col-xl-4"></div>').append($card);
                $grid.append($col);

                // Load courts per club
                $.ajax({
                    url: `/api/admin/courts/by-club/${club.id}`,
                    type: 'GET',
                    success: courts => {
                        courtTotal += courts.length;
                        renderCourtList($card, club, courts);
                    },
                    complete: () => {
                        pending--;
                        if (pending === 0) onStats({ clubs: clubs.length, courts: courtTotal });
                    }
                });
            });

            $container.append($grid);
            onStats({ clubs: clubs.length, courts: 0 }); // update when done
        },
        error: () => $container.html('<div class="alert alert-danger">Ошибка загрузки клубов</div>')
    });
}

function buildClubCard(club) {
    const firstImage = club.images && club.images.length > 0 ? club.images[0] : null;

    const $card = $(`
        <div class="club-card" data-club-id="${club.id}">
            <div class="card-img-wrap">
                ${firstImage
                    ? `<img src="${firstImage}" alt="${club.name}">`
                    : `<div class="card-img-placeholder"><i class="bi bi-building"></i></div>`}
            </div>
            <div class="club-name">${esc(club.name)}</div>
            <div class="club-info">
                ${club.address ? `<div class="info-item"><i class="bi bi-geo-alt"></i>${esc(club.address)}</div>` : ''}
                ${club.phone   ? `<div class="info-item"><i class="bi bi-telephone"></i>${esc(club.phone)}</div>`   : ''}
                ${club.email   ? `<div class="info-item"><i class="bi bi-envelope"></i>${esc(club.email)}</div>`   : ''}
            </div>
            ${club.description ? `<p class="text-muted small mb-2">${esc(club.description)}</p>` : ''}
            ${club.conveniences ? `<p class="small text-muted mb-2"><i class="bi bi-check-circle text-success me-1"></i>${esc(club.conveniences)}</p>` : ''}
            ${club.contactPhone ? `<div class="small text-muted mb-1"><i class="bi bi-telephone-forward me-1 text-success"></i><b>Публичный тел.:</b> ${esc(club.contactPhone)}${club.contactPerson ? ' (' + esc(club.contactPerson) + ')' : ''}</div>` : ''}
            ${club.telegramLink ? `<div class="small text-muted mb-2"><i class="bi bi-telegram me-1" style="color:#0088cc"></i><b>Telegram:</b> ${esc(club.telegramLink)}</div>` : ''}
            <div class="d-flex gap-2 mt-2 flex-wrap">
                <button class="btn-admin btn-sm edit-club-btn">
                    <i class="bi bi-pencil me-1"></i>Редактировать
                </button>
            </div>
            <div class="club-courts-section mt-3 pt-3" style="border-top:1px solid #e9ecef">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="fw-semibold small" style="color:#495057"><i class="bi bi-grid me-1 text-success"></i>Корты</span>
                    <button class="btn btn-sm add-court-btn"
                            style="background:var(--tennis-green);color:#fff;border:none;border-radius:6px;padding:3px 10px;font-size:0.78rem;font-weight:600">
                        <i class="bi bi-plus-lg me-1"></i>Добавить корт
                    </button>
                </div>
                <div class="club-courts-list">
                    <div class="text-muted small text-center py-2">
                        <span class="spinner-border spinner-border-sm"></span>
                    </div>
                </div>
            </div>
        </div>
    `);

    $card.on('click', '.edit-club-btn', () => openClubModal(club));
    $card.on('click', '.add-court-btn', () => openCourtModal(null, club.id));
    return $card;
}

function renderCourtList($card, club, courts) {
    const $list = $card.find('.club-courts-list');
    $list.empty();

    if (!courts || courts.length === 0) {
        $list.html('<div class="text-muted small text-center py-2">Кортов нет</div>');
        return;
    }

    courts.forEach(court => {
        const outdoor = court.isOutdoor ? '<span class="badge bg-info text-dark ms-1" style="font-size:0.65rem">Открытый</span>' : '<span class="badge bg-secondary ms-1" style="font-size:0.65rem">Крытый</span>';
        const visible = court.isVisible
            ? '<span class="badge bg-success ms-1" style="font-size:0.65rem">Видимый</span>'
            : '<span class="badge bg-warning text-dark ms-1" style="font-size:0.65rem">Скрытый</span>';

        const $item = $(`
            <div class="court-item" data-court-id="${court.id}">
                <div style="min-width:0;flex:1">
                    <div class="court-name d-flex align-items-center flex-wrap gap-1">
                        ${esc(court.name)}${outdoor}${visible}
                    </div>
                    <div class="court-details mt-1">
                        ${court.price ? `<span><i class="bi bi-currency-ruble me-1"></i>${court.price} ₽/час</span>` : ''}
                        ${court.cover ? `<span><i class="bi bi-layers me-1"></i>${esc(court.cover)}</span>` : ''}
                    </div>
                    ${court.description ? `<div class="text-muted" style="font-size:0.78rem;margin-top:2px">${esc(court.description)}</div>` : ''}
                </div>
                <div class="d-flex gap-1 ms-2 flex-shrink-0">
                    <button class="btn btn-sm edit-court-btn"
                            style="background:#e9ecef;border:none;border-radius:6px;padding:3px 8px;font-size:0.78rem">
                        <i class="bi bi-pencil"></i>
                    </button>
                    <button class="btn btn-sm delete-court-btn"
                            style="background:#fde8e8;color:#c0392b;border:none;border-radius:6px;padding:3px 8px;font-size:0.78rem">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
        `);

        $item.on('click', '.edit-court-btn',   () => openCourtModal(court, club.id));
        $item.on('click', '.delete-court-btn', () => deleteCourt(court.id, $card, club));
        $list.append($item);
    });
}

function buildEmpty() {
    return `<div class="text-center py-5 text-muted">
        <i class="bi bi-building 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-club-modal">
            <i class="bi bi-plus-circle me-1"></i>Создать клуб
        </button>
    </div>`;
}

// ════════════════════════════════════════════════════════
// CLUB MODAL
// ════════════════════════════════════════════════════════

function buildClubModal() {
    return `
    <div class="modal fade" id="create-club-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-building-add"></i></div>
                        <h5 class="modal-title mb-0" id="club-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="club-image-zone" class="mb-4"></div>

                    <p class="modal-section-label">Основное</p>
                    <div class="row g-3 mb-4">
                        <div class="col-12">
                            <div class="form-floating">
                                <input type="text" class="form-control rounded-3" id="club-name" placeholder=" ">
                                <label for="club-name">Название <span class="text-danger">*</span></label>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-floating">
                                <input type="text" class="form-control rounded-3" id="club-address" placeholder=" ">
                                <label for="club-address"><i class="bi bi-geo-alt me-1"></i>Адрес</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="text" class="form-control rounded-3" id="club-phone" placeholder=" ">
                                <label for="club-phone"><i class="bi bi-telephone me-1"></i>Телефон</label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-floating">
                                <input type="email" class="form-control rounded-3" id="club-email" placeholder=" ">
                                <label for="club-email"><i class="bi bi-envelope me-1"></i>Email (для уведомлений)</label>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-floating">
                                <input type="text" class="form-control rounded-3" id="club-website" placeholder=" ">
                                <label for="club-website"><i class="bi bi-globe me-1"></i>Сайт</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="text" class="form-control rounded-3" id="club-contact-phone" placeholder=" ">
                                <label for="club-contact-phone"><i class="bi bi-telephone me-1"></i>Публичный телефон</label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-floating">
                                <input type="text" class="form-control rounded-3" id="club-contact-person" placeholder=" ">
                                <label for="club-contact-person"><i class="bi bi-person me-1"></i>Имя контактного лица</label>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-floating">
                                <input type="text" class="form-control rounded-3" id="club-telegram" placeholder=" ">
                                <label for="club-telegram"><i class="bi bi-telegram me-1"></i>Telegram (@username или t.me/...</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="club-description"
                                          placeholder=" " style="height:80px"></textarea>
                                <label for="club-description">Описание</label>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-floating">
                                <input type="text" class="form-control rounded-3" id="club-conveniences" placeholder=" ">
                                <label for="club-conveniences"><i class="bi bi-check2-circle me-1"></i>Удобства (через запятую)</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-club-btn">
                        <i class="bi bi-check-lg me-1"></i><span id="save-club-label">Создать клуб</span>
                    </button>
                </div>
            </div>
        </div>
    </div>`;
}

function setupClubModal() {
    clubUploader = createImageUploader($('#club-image-zone'), '/api/admin/upload/image');

    $('#create-club-modal').on('show.bs.modal', (e) => {
        if (!e.relatedTarget && editingClubId === null) clearClubForm();
        $('#save-club-btn').off('click.save').on('click.save', saveClub);
    });
}

function openClubModal(club = null) {
    editingClubId = club ? club.id : null;

    if (club) {
        $('#club-modal-title').text('Редактировать клуб');
        $('#save-club-label').text('Сохранить');
        $('#club-name').val(club.name || '');
        $('#club-phone').val(club.phone || '');
        $('#club-email').val(club.email || '');
        $('#club-website').val(club.website || '');
        $('#club-address').val(club.address || '');
        $('#club-description').val(club.description || '');
        $('#club-conveniences').val(club.conveniences || '');
        $('#club-contact-phone').val(club.contactPhone || '');
        $('#club-contact-person').val(club.contactPerson || '');
        $('#club-telegram').val(club.telegramLink || '');
        clubUploader && clubUploader.setUrl(club.images && club.images.length > 0 ? club.images[0] : null);
    } else {
        clearClubForm();
    }

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

function clearClubForm() {
    editingClubId = null;
    $('#club-modal-title').text('Создать теннисный клуб');
    $('#save-club-label').text('Создать клуб');
    $('#club-name,#club-phone,#club-email,#club-website,#club-address,#club-description,#club-conveniences').val('');
    $('#club-contact-phone,#club-contact-person,#club-telegram').val('');
    clubUploader && clubUploader.reset();
}

function saveClub() {
    const name = $('#club-name').val().trim();
    if (!name) { alert('Название обязательно'); return; }

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

    const imageUrl = clubUploader ? clubUploader.getUrl() : null;
    const payload = {
        name,
        phone:         $('#club-phone').val().trim()         || null,
        email:         $('#club-email').val().trim()         || null,
        website:       $('#club-website').val().trim()       || null,
        address:       $('#club-address').val().trim()       || null,
        description:   $('#club-description').val().trim()   || null,
        conveniences:  $('#club-conveniences').val().trim()  || null,
        contactPhone:  $('#club-contact-phone').val().trim() || null,
        contactPerson: $('#club-contact-person').val().trim()|| null,
        telegramLink:  $('#club-telegram').val().trim()      || null,
        images:        imageUrl ? [imageUrl] : []
    };

    const isEdit = editingClubId !== null;
    $.ajax({
        url:         isEdit ? `/api/admin/clubs/${editingClubId}` : '/api/admin/clubs',
        type:        isEdit ? 'PUT' : 'POST',
        contentType: 'application/json',
        data:        JSON.stringify(payload),
        beforeSend:  xhr => xhr.setRequestHeader('X-XSRF-TOKEN', getCsrfToken()),
        success: () => {
            bootstrap.Modal.getInstance(document.getElementById('create-club-modal')).hide();
            loadClubs($globalContainer, globalOnStats);
        },
        error:    () => alert(isEdit ? 'Ошибка при обновлении клуба' : 'Ошибка при создании клуба'),
        complete: () => $btn.html(orig).prop('disabled', false)
    });
}

// ════════════════════════════════════════════════════════
// COURT MODAL
// ════════════════════════════════════════════════════════

function buildCourtModal() {
    return `
    <div class="modal fade" id="create-court-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" style="background:linear-gradient(135deg,#1e3a2f,#2ecc71)">
                    <div class="d-flex align-items-center gap-2">
                        <div class="modal-header-icon"><i class="bi bi-grid"></i></div>
                        <h5 class="modal-title mb-0" id="court-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="court-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="court-name" placeholder=" ">
                                <label for="court-name">Название корта <span class="text-danger">*</span></label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-floating">
                                <input type="number" class="form-control rounded-3" id="court-price"
                                       placeholder=" " min="0" step="50">
                                <label for="court-price"><i class="bi bi-currency-ruble me-1"></i>Цена/час (₽) <span class="text-danger">*</span></label>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-floating">
                                <input type="text" class="form-control rounded-3" id="court-description" placeholder=" ">
                                <label for="court-description">Описание</label>
                            </div>
                        </div>
                    </div>

                    <p class="modal-section-label">Характеристики</p>
                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label class="form-label fw-semibold small">Тип покрытия</label>
                            <select class="form-select rounded-3" id="court-cover">
                                <option value="">— не указано —</option>
                                <option value="Хард">Хард</option>
                                <option value="Грунт">Грунт</option>
                                <option value="Трава">Трава</option>
                                <option value="Ковёр">Ковёр</option>
                                <option value="Синтетика">Синтетика</option>
                                <option value="Искусственная трава">Искусственная трава</option>
                            </select>
                        </div>
                        <div class="col-md-6 d-flex flex-column gap-3 justify-content-center">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" role="switch"
                                       id="court-outdoor" style="cursor:pointer">
                                <label class="form-check-label fw-semibold" for="court-outdoor">
                                    Открытый корт (на улице)
                                </label>
                            </div>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" role="switch"
                                       id="court-visible" checked style="cursor:pointer">
                                <label class="form-check-label fw-semibold" for="court-visible">
                                    Показывать на сайте
                                </label>
                            </div>
                        </div>
                    </div>

                    <div id="court-error" class="alert alert-danger" style="display:none"></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 fw-semibold px-4 rounded-3" id="save-court-btn"
                            style="background:var(--tennis-green);color:#fff;border:none">
                        <i class="bi bi-check-lg me-1"></i><span id="save-court-label">Добавить корт</span>
                    </button>
                </div>
            </div>
        </div>
    </div>`;
}

function setupCourtModal() {
    courtUploader = createImageUploader($('#court-image-zone'), '/api/admin/upload/image');

    $('#create-court-modal').on('show.bs.modal', () => {
        $('#court-error').hide();
        $('#save-court-btn').off('click.save').on('click.save', saveCourt);
    });

    $('#create-court-modal').on('hidden.bs.modal', () => {
        editingCourtId = null;
        courtClubId    = null;
        $('#court-name,#court-description').val('');
        $('#court-price').val('');
        $('#court-cover').val('');
        $('#court-outdoor').prop('checked', false);
        $('#court-visible').prop('checked', true);
        courtUploader && courtUploader.reset();
        $('#court-error').hide();
        const $btn = $('#save-court-btn');
        $btn.html('<i class="bi bi-check-lg me-1"></i><span id="save-court-label">Добавить корт</span>').prop('disabled', false);
    });
}

function openCourtModal(court, clubId) {
    courtClubId    = clubId;
    editingCourtId = court ? court.id : null;

    if (court) {
        $('#court-modal-title').text('Редактировать корт');
        $('#save-court-label').text('Сохранить');
        $('#court-name').val(court.name || '');
        $('#court-description').val(court.description || '');
        $('#court-price').val(court.price != null ? court.price : '');
        $('#court-cover').val(court.cover || '');
        $('#court-outdoor').prop('checked', !!court.isOutdoor);
        $('#court-visible').prop('checked', court.isVisible !== false);
        courtUploader && courtUploader.setUrl(court.photo || null);
    } else {
        $('#court-modal-title').text('Добавить корт');
        $('#save-court-label').text('Добавить корт');
    }

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

function saveCourt() {
    const name  = $('#court-name').val().trim();
    const price = parseInt($('#court-price').val(), 10);

    if (!name)           { showCourtError('Введите название корта'); return; }
    if (!price || price < 0) { showCourtError('Введите корректную цену'); return; }

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

    const photo = courtUploader ? courtUploader.getUrl() : null;
    const payload = {
        clubUuid:    courtClubId,
        name,
        description: $('#court-description').val().trim() || null,
        photo:       photo || null,
        price,
        cover:       $('#court-cover').val() || null,
        isOutdoor:   $('#court-outdoor').is(':checked'),
        isVisible:   $('#court-visible').is(':checked')
    };

    const isEdit = editingCourtId !== null;
    $.ajax({
        url:         isEdit ? `/api/admin/courts/${editingCourtId}` : '/api/admin/courts',
        type:        isEdit ? 'PUT' : 'POST',
        contentType: 'application/json',
        data:        JSON.stringify(payload),
        beforeSend:  xhr => xhr.setRequestHeader('X-XSRF-TOKEN', getCsrfToken()),
        success: () => {
            bootstrap.Modal.getInstance(document.getElementById('create-court-modal')).hide();
            loadClubs($globalContainer, globalOnStats);
        },
        error:    () => { showCourtError(isEdit ? 'Ошибка при обновлении корта' : 'Ошибка при создании корта'); $btn.html(orig).prop('disabled', false); },
    });
}

function deleteCourt(courtId, $card, club) {
    if (!confirm('Удалить этот корт?')) return;

    $.ajax({
        url:  `/api/admin/courts/${courtId}`,
        type: 'DELETE',
        beforeSend: xhr => xhr.setRequestHeader('X-XSRF-TOKEN', getCsrfToken()),
        success: () => {
            // Reload courts for this card only
            $.ajax({
                url: `/api/admin/courts/by-club/${club.id}`,
                type: 'GET',
                success: courts => renderCourtList($card, club, courts)
            });
        },
        error: () => alert('Ошибка при удалении корта')
    });
}

function showCourtError(msg) {
    $('#court-error').text(msg).show();
}

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

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