import { getCsrfToken, formatDate, formatTime, eventTypeLabel } from '../../utils/helpers.js';
import { openApplyModal } from '../home/applyModal.js';

const clubId = window.clubId;

// ────────────────────────────────────────────────────────
// BOOT
// ────────────────────────────────────────────────────────

$(function () {
    if (!clubId) {
        $('#club-body').html('<div class="alert alert-danger my-5">Клуб не найден</div>');
        return;
    }

    $.ajax({
        url: `/api/clubs/${clubId}`,
        type: 'GET',
        success: club => renderClub(club),
        error: () => {
            $('#club-hero-inner').html('<h2 class="fw-bold">Клуб не найден</h2>');
            $('#club-body').html('<div class="alert alert-danger my-5">Не удалось загрузить данные клуба</div>');
        }
    });
});

// ────────────────────────────────────────────────────────
// RENDER
// ────────────────────────────────────────────────────────

function renderClub(club) {
    renderHero(club);
    renderBody(club);
    buildBookingModal(club);
}

function renderHero(club) {
    const images = club.images && club.images.length > 0 ? club.images : null;
    const firstImg = images ? images[0] : 'https://placehold.co/1200x400/2c3e50/ffffff?text=Tennis+Club';

    document.getElementById('club-hero').style.backgroundImage = `url('${esc(firstImg)}')`;

    const dots = images && images.length > 1
        ? `<div class="d-flex gap-2 mt-3" id="gallery-dots">
               ${images.map((_, i) =>
                   `<button class="gallery-dot ${i === 0 ? 'active' : ''}" data-idx="${i}"></button>`
               ).join('')}
           </div>`
        : '';

    $('#club-hero-inner').html(`
        <a href="/" class="text-white text-decoration-none small opacity-75 mb-2 d-inline-block">
            <i class="bi bi-arrow-left me-1"></i>Назад к клубам
        </a>
        <h1 class="club-hero-title mb-1">${esc(club.name)}</h1>
        ${club.address ? `<p class="mb-0 opacity-75"><i class="bi bi-geo-alt me-1"></i>${esc(club.address)}</p>` : ''}
        ${dots}
    `);

    if (images && images.length > 1) {
        let current = 0;
        $('#gallery-dots').on('click', '.gallery-dot', function () {
            current = parseInt($(this).data('idx'));
            document.getElementById('club-hero').style.backgroundImage = `url('${esc(images[current])}')`;
            $('#gallery-dots .gallery-dot').removeClass('active');
            $(this).addClass('active');
        });
    }
}

function renderBody(club) {
    const $body = $('#club-body');
    $body.empty();

    // ── Info + contacts ──
    const $info = $('<div class="club-section row g-4"></div>');

    // Description
    const $descCol = $('<div class="col-12 col-lg-8"></div>');
    if (club.description) {
        $descCol.append(`
            <h2 class="section-title">О клубе</h2>
            <p style="color:#555;line-height:1.7">${esc(club.description)}</p>
        `);
    }
    if (club.conveniences) {
        $descCol.append(`
            <div class="mt-3">
                <h6 class="fw-bold text-muted small text-uppercase mb-2">Удобства</h6>
                <p style="color:#555">${esc(club.conveniences)}</p>
            </div>
        `);
    }
    if (club.website) {
        $descCol.append(`
            <a href="${esc(club.website)}" target="_blank" rel="noopener" class="btn btn-sm btn-outline-secondary mt-2">
                <i class="bi bi-globe me-1"></i>Сайт клуба
            </a>
        `);
    }

    // Contacts
    const $ctaCol = $('<div class="col-12 col-lg-4"></div>');
    const contactItems = buildContactItems(club);
    if (contactItems.length > 0) {
        $ctaCol.append(`
            <h2 class="section-title">Контакты</h2>
            <div class="contact-card">
                ${contactItems.join('')}
            </div>
        `);
    }

    $info.append($descCol).append($ctaCol);
    $body.append($info);

    // ── Courts ──
    if (club.courts && club.courts.length > 0) {
        const $courtsSection = $('<div class="club-section"></div>');
        $courtsSection.append(`<h2 class="section-title">Корты</h2>`);
        const $row = $('<div class="row g-4"></div>');
        club.courts.forEach(court => {
            const $card = buildCourtCard(court, club);
            $row.append($card);
        });
        $courtsSection.append($row);
        $body.append($courtsSection);
    }

    // ── Upcoming events ──
    if (club.upcomingEvents && club.upcomingEvents.length > 0) {
        $body.append(buildEventsSection('Предстоящие мероприятия', club.upcomingEvents, true));
    }

    // ── Past events ──
    if (club.pastEvents && club.pastEvents.length > 0) {
        $body.append(buildEventsSection('Прошедшие мероприятия', club.pastEvents, false));
    }
}

function buildContactItems(club) {
    const items = [];

    if (club.contactPhone) {
        const person = club.contactPerson ? `<span class="text-muted small">${esc(club.contactPerson)}</span><br>` : '';
        items.push(`
            <div class="contact-item">
                <div class="contact-icon" style="background:#e8f8ef;color:var(--tennis-green)">
                    <i class="bi bi-telephone"></i>
                </div>
                <div>
                    ${person}
                    <a href="tel:${esc(club.contactPhone)}" class="fw-semibold text-decoration-none" style="color:var(--tennis-dark)">${esc(club.contactPhone)}</a>
                </div>
            </div>`);
    }

    if (club.telegramLink) {
        const tgDisplay = club.telegramLink.startsWith('@') ? club.telegramLink : '@' + club.telegramLink.replace(/^https?:\/\/t\.me\//,'');
        const tgHref = club.telegramLink.startsWith('http') ? club.telegramLink : `https://t.me/${club.telegramLink.replace(/^@/,'')}`;
        items.push(`
            <div class="contact-item">
                <div class="contact-icon" style="background:#e8f4fd;color:#0088cc">
                    <i class="bi bi-telegram"></i>
                </div>
                <div>
                    <a href="${esc(tgHref)}" target="_blank" rel="noopener" class="fw-semibold text-decoration-none" style="color:#0088cc">${esc(tgDisplay)}</a>
                </div>
            </div>`);
    }

    if (!club.contactPhone && !club.telegramLink && club.phone) {
        items.push(`
            <div class="contact-item">
                <div class="contact-icon" style="background:#e8f8ef;color:var(--tennis-green)">
                    <i class="bi bi-telephone"></i>
                </div>
                <div>
                    <a href="tel:${esc(club.phone)}" class="fw-semibold text-decoration-none" style="color:var(--tennis-dark)">${esc(club.phone)}</a>
                </div>
            </div>`);
    }

    return items;
}

function buildCourtCard(court, club) {
    const img = court.photo || 'https://placehold.co/400x180/e8f8ef/2c3e50?text=Корт';
    const outdoor = court.isOutdoor ? '<span class="badge bg-info text-dark me-1">Открытый</span>' : '<span class="badge bg-secondary me-1">Крытый</span>';
    const cover = court.cover ? `<span class="court-cover-badge">${esc(court.cover)}</span>` : '';
    const price = court.price ? `<span class="fw-bold" style="color:var(--tennis-green)">${court.price} ₽/час</span>` : '';

    const $col = $(`<div class="col-12 col-md-6 col-lg-4"></div>`);
    const $card = $(`
        <div class="court-card">
            <img src="${esc(img)}" class="court-img" alt="${esc(court.name)}">
            <div class="p-3">
                <h5 class="fw-bold mb-1">${esc(court.name)}</h5>
                ${court.description ? `<p class="text-muted small mb-2">${esc(court.description)}</p>` : ''}
                <div class="d-flex flex-wrap gap-1 align-items-center mb-2">
                    ${outdoor}${cover}
                </div>
                <div class="d-flex justify-content-between align-items-center mb-3">
                    ${price}
                </div>
                <button class="court-book-btn" data-court-id="${court.id}" data-court-name="${esc(court.name)}">
                    <i class="bi bi-calendar-check me-1"></i>Забронировать
                </button>
            </div>
        </div>
    `);

    $card.on('click', '.court-book-btn', function () {
        openBookingModal(club, court);
    });

    $col.append($card);
    return $col;
}

function buildEventsSection(title, events, isUpcoming) {
    const $section = $(`<div class="club-section"></div>`);
    $section.append(`<h2 class="section-title">${title}</h2>`);
    const $row = $('<div class="row g-3"></div>');
    events.forEach(e => $row.append(buildEventCard(e, isUpcoming)));
    $section.append($row);
    return $section;
}

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

    const applyBtn = isUpcoming && event.registrationOpen !== false
        ? `<button class="btn btn-sm fw-semibold mt-2 w-100 apply-event-btn"
                   data-event-id="${event.id}"
                   style="background:var(--tennis-green);color:#fff;border:none;border-radius:8px">
               <i class="bi bi-send me-1"></i>Подать заявку
           </button>`
        : isUpcoming
            ? `<button class="btn btn-sm fw-semibold mt-2 w-100 disabled" disabled
                       style="background:#e9ecef;color:#6c757d;border:none;border-radius:8px">
                   <i class="bi bi-lock me-1"></i>Приём закрыт
               </button>`
            : '';

    const $col = $('<div class="col-12 col-md-6 col-lg-4"></div>');
    const $card = $(`
        <div class="ev-card h-100">
            <div class="d-flex justify-content-between align-items-start mb-2">
                <h6 class="fw-bold mb-0">${esc(event.title)}</h6>
                <span class="ev-type-badge ${badgeClass} ms-2 flex-shrink-0">${eventTypeLabel(event.type)}</span>
            </div>
            ${event.description ? `<p class="text-muted small mb-2">${esc(event.description)}</p>` : ''}
            <div class="text-muted small">
                <i class="bi bi-calendar me-1"></i>${formatDate(event.startDateTime)}
                <i class="bi bi-clock ms-2 me-1"></i>${formatTime(event.startDateTime)}
            </div>
            ${event.takePartPrice != null
                ? `<div class="fw-bold mt-1" style="color:var(--tennis-green)">${event.takePartPrice > 0 ? event.takePartPrice + ' ₽' : 'Бесплатно'}</div>`
                : ''}
            ${applyBtn}
        </div>
    `);

    $card.on('click', '.apply-event-btn', () => openApplyModal(event));

    $col.append($card);
    return $col;
}

// ────────────────────────────────────────────────────────
// BOOKING MODAL
// ────────────────────────────────────────────────────────

let _currentClub = null;
let _currentCourt = null;
let _selectedTime = null;
let _selectedDuration = null;

function buildBookingModal(club) {
    if ($('#court-booking-modal').length) return;

    $('body').append(`
        <div class="modal fade" id="court-booking-modal" tabindex="-1">
            <div class="modal-dialog modal-dialog-centered modal-lg">
                <div class="modal-content border-0 rounded-4 overflow-hidden" style="box-shadow:0 20px 60px rgba(0,0,0,0.18)">
                    <div id="booking-modal-header" style="padding:18px 24px;display:flex;align-items:center;justify-content:space-between;background:linear-gradient(135deg,#2c3e50,#34495e)">
                        <div class="d-flex align-items-center gap-2">
                            <div style="width:36px;height:36px;border-radius:8px;background:rgba(255,255,255,0.15);display:flex;align-items:center;justify-content:center;color:#fff;font-size:1rem">
                                <i class="bi bi-calendar-check"></i>
                            </div>
                            <div>
                                <h5 class="modal-title mb-0 text-white fw-bold">Бронирование корта</h5>
                                <p class="mb-0 text-white opacity-75 small" id="booking-court-subtitle"></p>
                            </div>
                        </div>
                        <button type="button" class="btn-close btn-close-white opacity-75" data-bs-dismiss="modal"></button>
                    </div>

                    <div class="modal-body p-4">
                        <div class="row g-4">
                            <!-- LEFT: date + time + duration -->
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label fw-semibold small">Дата <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control rounded-3" id="booking-date"
                                           min="${todayISO()}">
                                </div>

                                <div class="mb-3">
                                    <label class="form-label fw-semibold small">Время начала <span class="text-danger">*</span></label>
                                    <div class="booking-time-grid" id="booking-time-grid"></div>
                                </div>

                                <div>
                                    <label class="form-label fw-semibold small">Длительность <span class="text-danger">*</span></label>
                                    <div class="d-flex flex-wrap gap-2" id="booking-duration-btns">
                                        ${[30,60,90,120,150,180].map(m =>
                                            `<button class="duration-btn" data-min="${m}">${durationLabel(m)}</button>`
                                        ).join('')}
                                    </div>
                                </div>
                            </div>

                            <!-- RIGHT: personal info -->
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label fw-semibold small">Ваше имя <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control rounded-3" id="booking-name" placeholder="Иван Иванов">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-semibold small">Email <span class="text-danger">*</span></label>
                                    <input type="email" class="form-control rounded-3" id="booking-email" placeholder="email@example.com">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-semibold small">Телефон</label>
                                    <input type="tel" class="form-control rounded-3" id="booking-phone" placeholder="+7 ...">
                                </div>
                                <div>
                                    <label class="form-label fw-semibold small">Сообщение</label>
                                    <textarea class="form-control rounded-3" id="booking-message" rows="3" placeholder="Дополнительная информация..."></textarea>
                                </div>
                            </div>
                        </div>

                        <div id="booking-summary" class="mt-3 p-3 rounded-3" style="background:#f8f9fa;display:none">
                            <div class="fw-semibold small text-muted mb-1">Ваш выбор:</div>
                            <div id="booking-summary-text" class="fw-bold"></div>
                        </div>

                        <div id="booking-error" class="alert alert-danger mt-3 mb-0" style="display:none"></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="booking-submit-btn"
                                style="background:var(--tennis-green);color:#fff;border:none">
                            <i class="bi bi-send me-1"></i>Отправить заявку
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `);

    setupBookingModal();
}

function setupBookingModal() {
    // Time grid: 06:00 — 23:00 in 30-min slots
    const slots = [];
    for (let h = 6; h <= 22; h++) {
        slots.push(`${pad(h)}:00`);
        slots.push(`${pad(h)}:30`);
    }
    const $grid = $('#booking-time-grid');
    slots.forEach(t => {
        $grid.append(`<button class="time-slot-btn" data-time="${t}">${t}</button>`);
    });

    $grid.on('click', '.time-slot-btn', function () {
        $grid.find('.time-slot-btn').removeClass('selected');
        $(this).addClass('selected');
        _selectedTime = $(this).data('time');
        updateSummary();
    });

    $('#booking-duration-btns').on('click', '.duration-btn', function () {
        $('#booking-duration-btns .duration-btn').removeClass('selected');
        $(this).addClass('selected');
        _selectedDuration = parseInt($(this).data('min'));
        updateSummary();
    });

    $('#booking-date').on('change', updateSummary);

    $('#court-booking-modal').on('hidden.bs.modal', () => {
        resetBookingModal();
    });

    $('#booking-submit-btn').on('click', submitBooking);
}

function openBookingModal(club, court) {
    _currentClub = club;
    _currentCourt = court;
    _selectedTime = null;
    _selectedDuration = null;

    resetBookingModal();
    $('#booking-court-subtitle').text(court.name);

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

function resetBookingModal() {
    _selectedTime = null;
    _selectedDuration = null;
    $('#booking-time-grid .time-slot-btn').removeClass('selected');
    $('#booking-duration-btns .duration-btn').removeClass('selected');
    $('#booking-date').val('');
    $('#booking-name').val('');
    $('#booking-email').val('');
    $('#booking-phone').val('');
    $('#booking-message').val('');
    $('#booking-summary').hide();
    $('#booking-error').hide();
    const $btn = $('#booking-submit-btn');
    $btn.html('<i class="bi bi-send me-1"></i>Отправить заявку').prop('disabled', false);
}

function updateSummary() {
    const date = $('#booking-date').val();
    if (date && _selectedTime && _selectedDuration) {
        const endTime = addMinutesToTime(_selectedTime, _selectedDuration);
        $('#booking-summary-text').text(
            `${formatDateRu(date)}, ${_selectedTime} — ${endTime} (${durationLabel(_selectedDuration)})`
        );
        $('#booking-summary').show();
    } else {
        $('#booking-summary').hide();
    }
}

function submitBooking() {
    const name  = $('#booking-name').val().trim();
    const email = $('#booking-email').val().trim();
    const phone = $('#booking-phone').val().trim();
    const date  = $('#booking-date').val();
    const msg   = $('#booking-message').val().trim();

    if (!name)           return showBookingError('Введите ваше имя');
    if (!email)          return showBookingError('Введите email');
    if (!date)           return showBookingError('Выберите дату');
    if (!_selectedTime)  return showBookingError('Выберите время начала');
    if (!_selectedDuration) return showBookingError('Выберите длительность');

    $('#booking-error').hide();
    const $btn = $('#booking-submit-btn');
    $btn.html('<span class="spinner-border spinner-border-sm me-1"></span>Отправка...').prop('disabled', true);

    $.ajax({
        url: `/api/clubs/${_currentClub.id}/booking-request`,
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            requesterName:  name,
            requesterEmail: email,
            requesterPhone: phone || null,
            courtId:  _currentCourt ? _currentCourt.id : null,
            bookingDate: date,
            startTime: _selectedTime,
            durationMinutes: _selectedDuration,
            message: msg || null
        }),
        beforeSend: xhr => xhr.setRequestHeader('X-XSRF-TOKEN', getCsrfToken()),
        success: resp => {
            bootstrap.Modal.getInstance(document.getElementById('court-booking-modal'))?.hide();
            showToast(resp.message || 'Заявка отправлена!', 'success');
        },
        error: (xhr) => {
            const msg = xhr.responseJSON?.message || 'Ошибка при отправке заявки';
            showBookingError(msg);
            $btn.html('<i class="bi bi-send me-1"></i>Отправить заявку').prop('disabled', false);
        }
    });
}

function showBookingError(msg) {
    $('#booking-error').text(msg).show();
}

// ────────────────────────────────────────────────────────
// HELPERS
// ────────────────────────────────────────────────────────

function durationLabel(minutes) {
    if (minutes < 60) return minutes + ' мин';
    const h = Math.floor(minutes / 60);
    const m = minutes % 60;
    return m > 0 ? `${h} ч ${m} мин` : `${h} ч`;
}

function pad(n) { return String(n).padStart(2, '0'); }

function addMinutesToTime(timeStr, minutes) {
    const [h, m] = timeStr.split(':').map(Number);
    const total = h * 60 + m + minutes;
    return `${pad(Math.floor(total / 60) % 24)}:${pad(total % 60)}`;
}

function formatDateRu(iso) {
    if (!iso) return '';
    const [y, m, d] = iso.split('-');
    return `${d}.${m}.${y}`;
}

function todayISO() {
    const d = new Date();
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`;
}

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

function showToast(msg, type = 'info') {
    const bg = type === 'success' ? '#2ecc71' : type === 'danger' ? '#e74c3c' : '#3498db';
    const id = 'toast-' + Date.now();
    const html = `
        <div id="${id}" class="toast align-items-center text-white border-0 show"
             style="background:${bg}" role="alert">
            <div class="d-flex">
                <div class="toast-body fw-semibold">${esc(msg)}</div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        </div>`;
    $('#info-toast').append(html);
    setTimeout(() => $(`#${id}`).remove(), 4000);
}
