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

const API = '/api/admin';

let editingPostId = null;
let galleryImageUploaders = [];
let $globalContainer;

function formatDate(dt) {
    if (!dt) return '—';
    return new Date(dt).toLocaleDateString('ru-RU', {
        day: 'numeric',
        month: 'long',
        year: 'numeric'
    });
}

function esc(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

export function initAdminGallery($container) {
    $globalContainer = $container;
    loadGalleryPosts();
    setupModal();
}

function loadGalleryPosts() {
    $globalContainer.html('<div class="text-center py-4"><div class="spinner-border text-success"></div></div>');

    $.ajax({
        url: `${API}/gallery`,
        type: 'GET',
        data: { page: 0, size: 50 },
        success: (response) => {
            $globalContainer.empty();
            const posts = response.content || [];

            if (posts.length === 0) {
                $globalContainer.html(`
                    <div class="text-center py-5 text-muted">
                        <i class="bi bi-images fs-1 d-block mb-3 opacity-50"></i>
                        <h5>Нет публикаций</h5>
                        <p>Создайте первую публикацию в галерее</p>
                    </div>
                `);
                return;
            }

            posts.forEach(post => {
                $globalContainer.append(renderCard(post));
            });
        },
        error: () => $globalContainer.html('<div class="alert alert-danger">Ошибка загрузки галереи</div>')
    });
}

function renderCard(post) {
    const imagesHtml = post.imageUrls && post.imageUrls.length > 0
        ? `<div class="admin-gallery-card-images">
               ${post.imageUrls.map(img => `<img src="${(window.cdn || '')}${img}" alt="img">`).join('')}
           </div>`
        : '<div class="text-muted small mb-2">Нет изображений</div>';

    const pubBadge = post.isPublished
        ? '<span class="badge bg-success">Опубликовано</span>'
        : '<span class="badge bg-warning text-dark">Черновик</span>';

    return $(`
        <div class="admin-gallery-card" data-post-id="${post.uuid}">
            <div class="d-flex justify-content-between align-items-start mb-2">
                <div>
                    <div class="admin-gallery-card-title">${esc(post.title)}</div>
                    <div class="admin-gallery-card-date">
                        <i class="bi bi-calendar3 me-1"></i>${formatDate(post.publishedAt || post.createdAt)}
                        ${pubBadge}
                    </div>
                </div>
                <div class="d-flex gap-1">
                    <button class="btn btn-sm btn-outline-primary edit-gallery-btn">
                        <i class="bi bi-pencil"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-danger delete-gallery-btn">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
            ${post.content ? `<div class="text-muted small mb-2">${esc(post.content).substring(0, 150)}${post.content.length > 150 ? '...' : ''}</div>` : ''}
            ${imagesHtml}
        </div>
    `).on('click', '.edit-gallery-btn', () => openEditModal(post))
      .on('click', '.delete-gallery-btn', () => deletePost(post.uuid));
}

function setupModal() {
    const modal = document.getElementById('gallery-post-modal');
    if (!modal) return;

    $('#add-gallery-post-btn').on('click', () => openCreateModal());

    const bsModal = bootstrap.Modal.getOrCreateInstance(modal);

    modal.addEventListener('shown.bs.modal', () => {
        initGalleryImageUploaders();
    });

    modal.addEventListener('hidden.bs.modal', () => {
        clearForm();
    });

    $('#save-gallery-post-btn').on('click', savePost);
}

function initGalleryImageUploaders() {
    const $zone = $('#gallery-images-zone');
    $zone.empty();
    galleryImageUploaders = [];

    // Render existing images or add new upload button
    const existingUrls = $zone.data('existing') || [];

    existingUrls.forEach((url, i) => {
        const uploaderId = `gallery-uploader-${i}`;
        $zone.append(`<div id="${uploaderId}" class="gallery-img-uploader"></div>`);
        const uploader = createSingleUploader($(`#${uploaderId}`), url);
        galleryImageUploaders.push(uploader);
    });

    // Add button
    $zone.append(`<div class="gallery-img-add" id="gallery-add-img-btn" title="Добавить изображение"><i class="bi bi-plus-lg"></i></div>`);

    $('#gallery-add-img-btn').on('click', function () {
        const idx = galleryImageUploaders.length;
        const uploaderId = `gallery-uploader-${idx}`;
        $(this).before(`<div id="${uploaderId}" class="gallery-img-uploader"></div>`);
        const uploader = createSingleUploader($(`#${uploaderId}`), null);
        galleryImageUploaders.push(uploader);
    });
}

function createSingleUploader($container, initialUrl) {
    let currentUrl = initialUrl;

    function render() {
        if (currentUrl) {
            const cdn = window.cdn || '';
            $container.html(`
                <div class="img-uploader__zone">
                    <img src="${cdn}${currentUrl}" class="img-uploader__preview" alt="preview">
                    <button class="img-uploader__remove" type="button"><i class="bi bi-x-lg"></i></button>
                </div>
            `);
            $container.find('.img-uploader__remove').on('click', (e) => {
                e.stopPropagation();
                currentUrl = null;
                render();
            });
        } else {
            $container.html(`
                <div class="img-uploader__zone">
                    <div class="img-uploader__placeholder">
                        <i class="bi bi-cloud-upload"></i>
                    </div>
                </div>
            `);
            $container.find('.img-uploader__zone').on('click', () => {
                const input = document.createElement('input');
                input.type = 'file';
                input.accept = 'image/*';
                input.onchange = async (e) => {
                    const file = e.target.files[0];
                    if (!file) return;
                    $container.find('.img-uploader__zone').addClass('uploading').html(
                        '<div class="img-uploader__loading"><div class="spinner-border text-light"></div></div>'
                    );
                    try {
                        currentUrl = await uploadImage(file);
                        render();
                    } catch (err) {
                        console.error(err);
                        $container.find('.img-uploader__zone').removeClass('uploading').html(
                            '<div class="img-uploader__placeholder"><i class="bi bi-exclamation-triangle text-danger"></i><span class="text-danger">Ошибка</span></div>'
                        );
                    }
                };
                input.click();
            });
        }
    }

    render();

    return {
        getUrl: () => currentUrl,
        setUrl: (url) => { currentUrl = url; render(); },
        clear: () => { currentUrl = null; render(); }
    };
}

async function uploadImage(file) {
    const formData = new FormData();
    formData.append('file', file);

    const res = await fetch(`${API}/upload/image`, {
        method: 'POST',
        headers: { 'X-XSRF-TOKEN': getCsrfToken() },
        body: formData,
    });

    if (!res.ok) throw new Error('Ошибка загрузки');
    const data = await res.json();
    return data.url;
}

function openCreateModal() {
    editingPostId = null;
    $('#gallery-modal-title').text('Новая публикация');
    bootstrap.Modal.getOrCreateInstance(document.getElementById('gallery-post-modal')).show();
}

function openEditModal(post) {
    editingPostId = post.uuid;
    $('#gallery-modal-title').text('Редактировать публикацию');
    $('#gallery-post-title').val(post.title || '');
    $('#gallery-post-content').val(post.content || '');
    $('#gallery-post-published').prop('checked', post.isPublished !== false);

    const $zone = $('#gallery-images-zone');
    $zone.data('existing', post.imageUrls || []);

    bootstrap.Modal.getOrCreateInstance(document.getElementById('gallery-post-modal')).show();
}

function clearForm() {
    editingPostId = null;
    $('#gallery-modal-title').text('Новая публикация');
    $('#gallery-post-title').val('');
    $('#gallery-post-content').val('');
    $('#gallery-post-published').prop('checked', true);
    const $zone = $('#gallery-images-zone');
    $zone.data('existing', []);
    $zone.empty();
    galleryImageUploaders = [];
}

function savePost() {
    const title = $('#gallery-post-title').val().trim();
    if (!title) { alert('Заголовок обязателен'); return; }

    const imageUrls = galleryImageUploaders
        .map(u => u.getUrl())
        .filter(u => u !== null);

    const payload = {
        title,
        content: $('#gallery-post-content').val().trim() || null,
        imageUrls: imageUrls.length > 0 ? imageUrls : null,
        isPublished: $('#gallery-post-published').is(':checked')
    };

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

    const isEdit = editingPostId !== null;
    $.ajax({
        url: isEdit ? `${API}/gallery/${editingPostId}` : `${API}/gallery`,
        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('gallery-post-modal')).hide();
            loadGalleryPosts();
        },
        error: () => alert(isEdit ? 'Ошибка при обновлении' : 'Ошибка при создании'),
        complete: () => $btn.html(orig).prop('disabled', false)
    });
}

function deletePost(id) {
    if (!confirm('Удалить эту публикацию?')) return;

    $.ajax({
        url: `${API}/gallery/${id}`,
        type: 'DELETE',
        beforeSend: xhr => xhr.setRequestHeader('X-XSRF-TOKEN', getCsrfToken()),
        success: () => loadGalleryPosts(),
        error: () => alert('Ошибка при удалении')
    });
}
