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

const API = '/api/admin';

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 initImageUploader(zoneId) {
    const zone = document.getElementById(zoneId);
    if (!zone) return { getUrl: () => null, setUrl: () => {}, clear: () => {} };

    let currentUrl = null;

    zone.addEventListener('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;
            zone.classList.add('uploading');
            zone.innerHTML = '<div class="img-uploader__loading"><div class="spinner-border text-light"></div></div>';
            try {
                currentUrl = await uploadImage(file);
                const cdn = window.cdn || '';
                zone.innerHTML = `<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>`;
                zone.querySelector('.img-uploader__remove').addEventListener('click', (ev) => {
                    ev.stopPropagation();
                    currentUrl = null;
                    zone.innerHTML = `<div class="img-uploader__placeholder">
                        <i class="bi bi-cloud-upload"></i>
                        <span>Нажмите или перетащите изображение</span>
                    </div>`;
                    if (window.onSiteImagesChange) window.onSiteImagesChange();
                });
                if (window.onSiteImagesChange) window.onSiteImagesChange();
            } catch (err) {
                console.error(err);
                zone.innerHTML = `<div class="img-uploader__placeholder">
                    <i class="bi bi-exclamation-triangle text-danger"></i>
                    <span class="text-danger">Ошибка загрузки</span>
                </div>`;
                setTimeout(() => {
                    zone.innerHTML = `<div class="img-uploader__placeholder">
                        <i class="bi bi-cloud-upload"></i>
                        <span>Нажмите или перетащите изображение</span>
                    </div>`;
                }, 2000);
            } finally {
                zone.classList.remove('uploading');
            }
        };
        input.click();
    });

    zone.addEventListener('dragover', (e) => { e.preventDefault(); zone.classList.add('dragover'); });
    zone.addEventListener('dragleave', () => zone.classList.remove('dragover'));
    zone.addEventListener('drop', async (e) => {
        e.preventDefault();
        zone.classList.remove('dragover');
        const file = e.dataTransfer.files[0];
        if (!file || !file.type.startsWith('image/')) return;
        zone.classList.add('uploading');
        zone.innerHTML = '<div class="img-uploader__loading"><div class="spinner-border text-light"></div></div>';
        try {
            currentUrl = await uploadImage(file);
            const cdn = window.cdn || '';
            zone.innerHTML = `<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>`;
            zone.querySelector('.img-uploader__remove').addEventListener('click', (ev) => {
                ev.stopPropagation();
                currentUrl = null;
                zone.innerHTML = `<div class="img-uploader__placeholder">
                    <i class="bi bi-cloud-upload"></i>
                    <span>Нажмите или перетащите изображение</span>
                </div>`;
                if (window.onSiteImagesChange) window.onSiteImagesChange();
            });
            if (window.onSiteImagesChange) window.onSiteImagesChange();
        } catch (err) {
            console.error(err);
            zone.innerHTML = `<div class="img-uploader__placeholder">
                <i class="bi bi-exclamation-triangle text-danger"></i>
                <span class="text-danger">Ошибка загрузки</span>
            </div>`;
            setTimeout(() => {
                zone.innerHTML = `<div class="img-uploader__placeholder">
                    <i class="bi bi-cloud-upload"></i>
                    <span>Нажмите или перетащите изображение</span>
                </div>`;
            }, 2000);
        } finally {
            zone.classList.remove('uploading');
        }
    });

    return {
        getUrl: () => currentUrl,
        setUrl: (url) => {
            currentUrl = url;
            if (url) {
                const cdn = window.cdn || '';
                zone.innerHTML = `<img src="${cdn}${url}" class="img-uploader__preview" alt="preview">
                                  <button class="img-uploader__remove" type="button"><i class="bi bi-x-lg"></i></button>`;
                zone.querySelector('.img-uploader__remove').addEventListener('click', (ev) => {
                    ev.stopPropagation();
                    currentUrl = null;
                    zone.innerHTML = `<div class="img-uploader__placeholder">
                        <i class="bi bi-cloud-upload"></i>
                        <span>Нажмите или перетащите изображение</span>
                    </div>`;
                    if (window.onSiteImagesChange) window.onSiteImagesChange();
                });
            }
        },
        clear: () => {
            currentUrl = null;
            zone.innerHTML = `<div class="img-uploader__placeholder">
                <i class="bi bi-cloud-upload"></i>
                <span>Нажмите или перетащите изображение</span>
            </div>`;
        }
    };
}

export async function initSiteImages() {
    const heroUploader = initImageUploader('hero-image-zone');
    const bgUploader = initImageUploader('bg-image-zone');
    const saveBtn = document.getElementById('save-site-images-btn');

    if (!saveBtn) return;

    window.onSiteImagesChange = () => {
        saveBtn.disabled = false;
    };

    // Загрузка текущих настроек
    try {
        const res = await fetch(`${API}/site-settings`, {
            headers: {
                'Accept': 'application/json',
                'X-XSRF-TOKEN': getCsrfToken()
            }
        });
        if (res.ok) {
            const settings = await res.json();
            if (settings.heroImageUrl) heroUploader.setUrl(settings.heroImageUrl);
            if (settings.backgroundImageUrl) bgUploader.setUrl(settings.backgroundImageUrl);
        }
    } catch (err) {
        console.error('Ошибка загрузки настроек изображений:', err);
    }

    saveBtn.addEventListener('click', async () => {
        saveBtn.disabled = true;
        saveBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Сохранение...';

        try {
            const body = {
                heroImageUrl: heroUploader.getUrl(),
                backgroundImageUrl: bgUploader.getUrl()
            };

            const res = await fetch(`${API}/site-settings`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'X-XSRF-TOKEN': getCsrfToken()
                },
                body: JSON.stringify(body)
            });

            if (!res.ok) throw new Error('Ошибка сохранения настроек');

            saveBtn.innerHTML = '<i class="bi bi-check-circle me-1"></i>Сохранено!';
            setTimeout(() => {
                saveBtn.innerHTML = '<i class="bi bi-check-circle me-1"></i>Сохранить изображения';
            }, 2000);
        } catch (err) {
            console.error(err);
            saveBtn.disabled = false;
            saveBtn.innerHTML = '<i class="bi bi-x-circle me-1"></i>Ошибка сохранения';
            setTimeout(() => {
                saveBtn.innerHTML = '<i class="bi bi-check-circle me-1"></i>Сохранить изображения';
            }, 2000);
        }
    });
}
