import './styles/upload_new.scss';
import $ from 'jquery';
import * as bootstrap from 'bootstrap';

$('.button-resend').on('click', function () {
    $(this).prop('disabled', true);
    $(this).closest('form').submit();
});

type ContactSuggestion = {
    id: number | string;
    text: string;
    email?: string;
    cellphone?: string | null;
    firstName?: string | null;
    lastName?: string | null;
    company?: string | null;
    hasCellphone?: boolean;
};

$(function () {
    document.querySelectorAll<HTMLElement>('[data-bs-toggle="tooltip"]').forEach((el) => {
        new bootstrap.Tooltip(el);
    });

    $('#spinner').hide();
    $('#form-area').css({opacity: '1'});
    $('.select2-close-mask').remove();

    const emailField = $('#shared_file_email');
    emailField.prop('required', true);

    const emailZone = document.getElementById('emailZone');
    const suggestionsEl = document.getElementById('emailSuggestions');
    const smsOutput = document.getElementById('output_sms');
    const contactSelect = document.getElementById('shared_file_contact') as HTMLSelectElement | null;
    const cellphoneInput = document.getElementById('shared_file_cellphone') as HTMLInputElement | null;
    const findContactsUrl = emailZone?.dataset.findContactsUrl || '';
    const smsEnabled = emailZone?.dataset.smsEnabled === '1';
    const smsLabel = emailZone?.dataset.smsLabel || 'Send code via SMS';

    let suggestTimer: number | undefined;
    let activeIndex = -1;
    let currentSuggestions: ContactSuggestion[] = [];

    function hideSuggestions(): void {
        if (!suggestionsEl) {
            return;
        }
        suggestionsEl.classList.add('d-none');
        suggestionsEl.innerHTML = '';
        activeIndex = -1;
        currentSuggestions = [];
    }

    function clearSmsOption(): void {
        if (smsOutput) {
            smsOutput.innerHTML = '';
        }
        if (contactSelect) {
            contactSelect.value = '';
        }
        if (cellphoneInput) {
            cellphoneInput.value = '';
        }
    }

    function showSmsOption(cellphone: string): void {
        if (!smsOutput || !smsEnabled || !cellphone) {
            clearSmsOption();
            return;
        }

        smsOutput.innerHTML = `
            <div class="upload-sms-option">
                <input type="checkbox" name="send_sms" id="send_sms" value="1">
                <label for="send_sms">${smsLabel}: ${cellphone}</label>
            </div>
        `;
        if (cellphoneInput) {
            cellphoneInput.value = cellphone;
        }
    }

    function applyContact(contact: ContactSuggestion): void {
        const email = contact.email || String(emailField.val() || '');
        emailField.val(email);

        if (contactSelect) {
            const option = new Option(contact.text || email, String(contact.id), true, true);
            contactSelect.innerHTML = '';
            contactSelect.appendChild(option);
            contactSelect.value = String(contact.id);
        }

        if (contact.hasCellphone && contact.cellphone) {
            showSmsOption(contact.cellphone);
        } else {
            clearSmsOption();
        }

        hideSuggestions();
    }

    function renderSuggestions(items: ContactSuggestion[]): void {
        if (!suggestionsEl) {
            return;
        }

        currentSuggestions = items;
        activeIndex = -1;
        suggestionsEl.innerHTML = '';

        if (!items.length) {
            hideSuggestions();
            return;
        }

        items.forEach((item, index) => {
            const li = document.createElement('li');
            li.setAttribute('role', 'option');

            const button = document.createElement('button');
            button.type = 'button';
            button.className = 'email-suggest__item';
            button.dataset.index = String(index);

            const nameParts = [item.firstName, item.lastName].filter(Boolean).join(' ');
            const metaParts = [item.company, nameParts].filter(Boolean).join(' · ');

            button.innerHTML = `
                <span>${item.email || item.text}</span>
                ${metaParts ? `<span class="email-suggest__meta">${metaParts}</span>` : ''}
            `;

            button.addEventListener('click', () => applyContact(item));
            li.appendChild(button);
            suggestionsEl.appendChild(li);
        });

        suggestionsEl.classList.remove('d-none');
    }

    function fetchSuggestions(query: string): void {
        if (!findContactsUrl || query.trim().length < 3) {
            hideSuggestions();
            return;
        }

        $.ajax({
            url: findContactsUrl,
            method: 'GET',
            data: {
                query: query.trim(),
                action: 'getContactsByQuery',
            },
            success: (response: { results?: ContactSuggestion[] }) => {
                renderSuggestions(response.results || []);
            },
            error: () => hideSuggestions(),
        });
    }

    function syncSmsForExactEmail(email: string): void {
        if (!findContactsUrl || !smsEnabled || email.trim().length < 3) {
            clearSmsOption();
            return;
        }

        $.ajax({
            url: findContactsUrl,
            method: 'GET',
            data: {
                query: email.trim(),
                action: 'getContactsByQuery',
            },
            success: (response: { results?: ContactSuggestion[] }) => {
                const match = (response.results || []).find(
                    (item) => (item.email || '').toLowerCase() === email.trim().toLowerCase()
                );

                if (match?.hasCellphone && match.cellphone) {
                    if (contactSelect) {
                        const option = new Option(match.text || match.email || email, String(match.id), true, true);
                        contactSelect.innerHTML = '';
                        contactSelect.appendChild(option);
                        contactSelect.value = String(match.id);
                    }
                    showSmsOption(match.cellphone);
                } else {
                    clearSmsOption();
                }
            },
        });
    }

    if (emailZone && suggestionsEl && findContactsUrl) {
        emailField.on('input', function () {
            const value = String($(this).val() || '');
            window.clearTimeout(suggestTimer);
            suggestTimer = window.setTimeout(() => fetchSuggestions(value), 250);

            if (value.trim().length < 3) {
                clearSmsOption();
            }
        });

        emailField.on('blur', function () {
            window.setTimeout(() => {
                hideSuggestions();
                syncSmsForExactEmail(String(emailField.val() || ''));
            }, 180);
        });

        emailField.on('keydown', function (event) {
            if (suggestionsEl.classList.contains('d-none') || !currentSuggestions.length) {
                return;
            }

            const items = suggestionsEl.querySelectorAll('.email-suggest__item');
            if (event.key === 'ArrowDown') {
                event.preventDefault();
                activeIndex = Math.min(activeIndex + 1, items.length - 1);
            } else if (event.key === 'ArrowUp') {
                event.preventDefault();
                activeIndex = Math.max(activeIndex - 1, 0);
            } else if (event.key === 'Enter' && activeIndex >= 0) {
                event.preventDefault();
                applyContact(currentSuggestions[activeIndex]);
                return;
            } else if (event.key === 'Escape') {
                hideSuggestions();
                return;
            } else {
                return;
            }

            items.forEach((item, index) => {
                item.classList.toggle('is-active', index === activeIndex);
            });
        });
    }

    $('#submitbutton').on('click', function () {
        const email = String(emailField.val() || '').trim();
        if (email) {
            $('#submitbutton').prop('disabled', true);
            $('#spinner').show();
            $('#form-area').css({opacity: '0.5'});
            $('form[name="shared_file"]').trigger('submit');
            return;
        }

        const errorHtml =
            '<div class="alert alert-warning alert-dismissible fade show" role="alert">' +
            'Bitte E-Mail-Adresse eintragen' +
            '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>';
        $('#output_email_empty').html(errorHtml);
        $('#output_email_empty_bottom').html(errorHtml);
    });
});
