import { ModalFactory } from '../../core/ModalFactory';

export class HrefEditor {
    private onChangeCallback: (fieldName: string, newValue: string) => void;

    constructor(onChangeCallback: (fieldName: string, newValue: string) => void) {
        this.onChangeCallback = onChangeCallback;
        this.initialize();
    }

    private initialize(): void {
        const links = document.querySelectorAll<HTMLAnchorElement>('[data-editable-href="true"]');
        this.bindLinks(Array.from(links));
    }

    /**
     * Wires badge + click-prevent onto links inserted after bootstrap (e.g. a dynamically
     * added block), mirroring EditorCore.bindEditableElement() for `data-editable-href`.
     *
     * Links carrying `data-label-field` (e.g. the Actualité block button) also open the
     * combined label+href modal on a click anywhere on the link, not just the badge —
     * there's no separate inline text-edit path for their label.
     */
    public bindLinks(links: HTMLAnchorElement[]): void {
        links.forEach(link => {
            this.addBadge(link);
            link.addEventListener('click', (e) => {
                e.preventDefault();
                if (link.dataset.labelField) {
                    this.openEditor(link);
                }
            });
        });
    }

    private addBadge(link: HTMLAnchorElement): void {
        const badge = document.createElement('span');
        badge.className = 'href-editor__badge';
        badge.textContent = '🔗';
        badge.style.cssText = `
            position: absolute;
            top: -12px;
            right: -12px;
            background: #4CAF50;
            color: white;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 12px;
            z-index: 100;
        `;

        link.style.position = 'relative';
        link.appendChild(badge);

        badge.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            this.openEditor(link);
        });
    }

    private openEditor(link: HTMLAnchorElement): void {
        const currentHref = link.getAttribute('href') || '';
        const fieldName = link.dataset.field || '';
        const labelField = link.dataset.labelField;
        const currentLabel = link.dataset.labelValue || '';

        const contentDiv = document.createElement('div');

        let labelInput: HTMLInputElement | null = null;
        if (labelField) {
            const labelTitle = document.createElement('label');
            labelTitle.textContent = 'Label du bouton';
            labelTitle.style.cssText = 'display: block; font-weight: 600; margin-top: 8px;';

            labelInput = document.createElement('input');
            labelInput.type = 'text';
            labelInput.value = currentLabel;
            labelInput.placeholder = 'Label du bouton';
            labelInput.style.cssText = 'width: 100%; padding: 8px; margin: 4px 0 16px;';

            contentDiv.appendChild(labelTitle);
            contentDiv.appendChild(labelInput);
        }

        const hrefTitle = document.createElement('label');
        hrefTitle.textContent = 'Lien';
        hrefTitle.style.cssText = 'display: block; font-weight: 600;';

        const input = document.createElement('input');
        input.type = 'text';
        input.value = currentHref;
        input.style.cssText = 'width: 100%; padding: 8px; margin: 4px 0 16px;';

        contentDiv.appendChild(hrefTitle);
        contentDiv.appendChild(input);

        const buttonsDiv = document.createElement('div');
        buttonsDiv.style.cssText = 'display: flex; gap: 8px; justify-content: flex-end;';

        const cancelBtn = document.createElement('button');
        cancelBtn.textContent = 'Annuler';
        cancelBtn.className = 'btn-secondary';

        const saveBtn = document.createElement('button');
        saveBtn.textContent = 'Enregistrer';
        saveBtn.className = 'btn-primary';

        buttonsDiv.appendChild(cancelBtn);
        buttonsDiv.appendChild(saveBtn);
        contentDiv.appendChild(buttonsDiv);

        const modal = ModalFactory.create({
            title: labelField ? 'Modifier le bouton' : 'Modifier le lien',
            content: contentDiv,
            backdropClick: true,
            onClose: () => {}
        });

        document.body.appendChild(modal);
        (labelInput || input).focus();

        const save = () => {
            const newHref = input.value.trim();
            link.setAttribute('href', newHref);
            link.dataset.href = newHref;
            this.onChangeCallback(fieldName, newHref);

            if (labelField && labelInput) {
                const newLabel = labelInput.value.trim();
                link.dataset.labelValue = newLabel;

                const target = link.querySelector<HTMLElement>('[data-label-target="true"]');
                if (target) {
                    target.textContent = newLabel || 'Label du bouton';
                    target.classList.toggle('is-empty', !newLabel);
                }

                this.onChangeCallback(labelField, newLabel);
            }

            ModalFactory.close(modal);
        };

        saveBtn.addEventListener('click', save);
        cancelBtn.addEventListener('click', () => ModalFactory.close(modal));
        [labelInput, input].forEach(field => {
            field?.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') save();
                if (e.key === 'Escape') ModalFactory.close(modal);
            });
        });
    }
}
