import axios from 'axios';

function showToast(message, type = 'error') {
    let container = document.querySelector('[data-role="toast-container"]');
    if (!container) {
        container = document.createElement('div');
        container.dataset.role = 'toast-container';
        container.style.position = 'fixed';
        container.style.top = '1rem';
        container.style.right = '1rem';
        container.style.zIndex = '9999';
        container.style.display = 'flex';
        container.style.flexDirection = 'column';
        container.style.gap = '0.5rem';
        document.body.appendChild(container);
    }

    const toast = document.createElement('div');
    toast.textContent = message;
    toast.style.padding = '0.6rem 0.9rem';
    toast.style.borderRadius = '6px';
    toast.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
    toast.style.color = '#0f172a';
    toast.style.fontSize = '0.9rem';
    toast.style.backgroundColor = type === 'success' ? '#bbf7d0' : '#fee2e2';

    container.appendChild(toast);

    setTimeout(() => {
        toast.remove();
        if (!container.children.length) {
            container.remove();
        }
    }, 3000);
}

function getPageRoot() {
    return document.querySelector('[data-page^="plan-"]');
}

function normalizeDetails(formData) {
    const details = {};

    for (const [key, value] of formData.entries()) {
        if (!key.startsWith('details[')) {
            continue;
        }

        const field = key.slice('details['.length, -1);
        if (value === '') {
            continue;
        }

        details[field] = value;
    }

    return details;
}

function parseRows(formData) {
    return formData.getAll('rows[]').map((value) => parseInt(value, 10)).filter((value) => !Number.isNaN(value));
}

function getPlannedDateFromUrl() {
    try {
        const params = new URLSearchParams(window.location.search);
        const value = params.get('date');
        return value || null;
    } catch (error) {
        console.error('Unable to read planned date from URL', error);
        return null;
    }
}

function buildPayload(form, actionKey) {
    const formData = new FormData(form);
    console.log(Object.fromEntries(formData.entries()));
    const payload = {
        action: actionKey,
        planned_date: getPlannedDateFromUrl(),
        execution_date: formData.get('execution_date') || null,
        note: formData.get('note') || null,
        rows: parseRows(formData),
        details: normalizeDetails(formData),
    };

    return payload;
}

export function init(actionKey) {
    const root = getPageRoot();
    if (!root) {
        return;
    }

    const storeUrl = root.dataset.storeUrl;
    const form = root.querySelector('form[data-role="planned-task-form"]');

    if (!form || !storeUrl) {
        return;
    }

    form.addEventListener('submit', async (event) => {
        event.preventDefault();

        const payload = buildPayload(form, actionKey);
        console.log(payload);

        if (payload.rows.length === 0) {
            showToast('Select at least one row for the planned task.', 'error');
            return;
        }

        try {
            const response = await axios.post(storeUrl, payload);   
            if (response.data?.success) {
                showToast('Planned tasks created successfully.', 'success');
                const url = new URL(window.location.href);
                url.pathname = '/vineyard/map';
                url.search = '';
                window.location.assign(url.toString());
            } else {
                showToast('Some rows could not be processed. Please review the details.', 'error');
            }
        } catch (error) {
            console.error('Failed to create planned tasks', error);

            const data = error.response?.data;
            if (data?.errors && typeof data.errors === 'object') {
                const messages = Object.values(data.errors)
                    .flat()
                    .filter((value) => typeof value === 'string');

                if (messages.length) {
                    showToast(messages[0], 'error');
                    return;
                }
            }

            if (data?.message && typeof data.message === 'string') {
                showToast(data.message, 'error');
                return;
            }

            showToast('Unable to create planned tasks. Please check the form inputs.', 'error');
        }
    });
}
