import { buildEndpoint } from './urlBuilder';

document.addEventListener('DOMContentLoaded', function () {
    initBillTable();
    initSupplierSearchAndQuickCreate();
    initBillCreatePanel();
});

function initBillTable() {
    const billTable = $('#billTable');

    if (!billTable.length) {
        return;
    }

    billTable.DataTable({
        processing: true,
        serverSide: true,
        scrollX: true,
        autoWidth: false,
        ajax: {
            url: buildEndpoint('admin-fit/bill/json'),
            type: 'GET'
        },
        columns: [
            { data: 'bill_identifier', name: 'bill_identifier', className: 'text-center' },
            { data: 'supplier_name', name: 'supplier_name', className: 'text-center' },
            {
                data: 'status',
                name: 'status',
                className: 'text-center',
                render: function (data) {
                    const status = String(data || '').toLowerCase();
                    const classes = {
                        pendiente: 'bg-warning text-dark',
                        completada: 'bg-success',
                        anulada: 'bg-danger'
                    };
                    const label = status ? status.charAt(0).toUpperCase() + status.slice(1) : 'N/A';
                    return `<span class="badge ${classes[status] || 'bg-secondary'}">${label}</span>`;
                }
            },
            { data: 'total_formatted', name: 'total', className: 'text-end' },
            { data: 'debt_formatted', name: 'debt', className: 'text-end' },
            { data: 'expiration_date', name: 'expiration_date', className: 'text-center' },
            {
                data: null,
                name: 'edit',
                className: 'text-center',
                orderable: false,
                searchable: false,
                render: function (data, type, row) {
                    return `
                        <a href="${buildEndpoint(`admin-fit/bill/${row.id}/edit`)}" class="btn btn-sm btn-warning">Editar</a>
                    `;
                }
            }
        ],
        columnDefs: [
            {
                targets: -1,
                className: 'text-center text-nowrap'
            }
        ],
        order: [[0, 'desc']],
        language: {
            processing: 'Procesando...',
            search: 'Buscar:',
            lengthMenu: 'Mostrar _MENU_ registros',
            info: 'Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros',
            infoEmpty: 'Mostrando registros del 0 al 0 de un total de 0 registros',
            infoFiltered: '(filtrado de un total de _MAX_ registros)',
            infoPostFix: '',
            loadingRecords: 'Cargando...',
            zeroRecords: 'No se encontraron resultados',
            emptyTable: 'Ningún dato disponible en esta tabla',
            paginate: {
                first: 'Primero',
                previous: 'Anterior',
                next: 'Siguiente',
                last: 'Último'
            },
            aria: {
                sortAscending: ': Activar para ordenar la columna de manera ascendente',
                sortDescending: ': Activar para ordenar la columna de manera descendente'
            }
        }
    });
}

function initSupplierSearchAndQuickCreate() {
    const searchInput = document.getElementById('supplier_search');
    const searchBtn = document.getElementById('supplierSearchBtn');
    const results = document.getElementById('supplierResults');
    const supplierIdInput = document.getElementById('supplier_id');
    const selectedLabel = document.getElementById('supplierSelectedLabel');
    const quickSupplierForm = document.getElementById('quickSupplierForm');
    const quickSupplierName = document.getElementById('quick_supplier_name');
    const quickSupplierError = document.getElementById('quickSupplierError');

    if (!searchInput || !supplierIdInput || !results || !selectedLabel) {
        return;
    }

    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';

    const setSelectedSupplier = (supplier) => {
        supplierIdInput.value = supplier.id;
        searchInput.value = supplier.supplier_name;
        selectedLabel.textContent = `Proveedor seleccionado: ${supplier.supplier_name}`;
        results.classList.add('d-none');
        results.innerHTML = '';
    };

    const renderResults = (items) => {
        if (!Array.isArray(items) || items.length === 0) {
            results.classList.remove('d-none');
            results.innerHTML = '<div class="list-group-item text-muted">Sin resultados</div>';
            return;
        }

        results.innerHTML = items.map((item) => {
            return `
                <button type="button" class="list-group-item list-group-item-action supplier-result-item" data-id="${item.id}" data-name="${item.supplier_name}">
                    ${item.supplier_name}
                </button>
            `;
        }).join('');

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

    const fetchSuppliers = (query) => {
        const searchTerm = (query || '').trim();
        if (searchTerm.length === 0) {
            results.classList.add('d-none');
            results.innerHTML = '';
            return;
        }

        fetch(buildEndpoint(`admin-fit/bill/supplier-search?q=${encodeURIComponent(searchTerm)}`), {
            method: 'GET',
            headers: {
                Accept: 'application/json'
            }
        })
            .then(async (response) => {
                const data = await response.json().catch(() => ({}));
                if (!response.ok || data.success === false) {
                    throw new Error(data.message || 'No se pudo buscar proveedores');
                }
                renderResults(data.data || []);
            })
            .catch((error) => {
                results.classList.remove('d-none');
                results.innerHTML = `<div class="list-group-item text-danger">${error.message || 'Error buscando proveedores'}</div>`;
            });
    };

    let searchDebounce = null;

    searchInput.addEventListener('input', function () {
        if (searchDebounce) {
            clearTimeout(searchDebounce);
        }

        searchDebounce = setTimeout(() => {
            fetchSuppliers(searchInput.value);
        }, 250);
    });

    if (searchBtn) {
        searchBtn.addEventListener('click', function () {
            fetchSuppliers(searchInput.value);
        });
    }

    results.addEventListener('click', function (event) {
        const target = event.target.closest('.supplier-result-item');
        if (!target) {
            return;
        }

        const selectedSupplier = {
            id: Number(target.getAttribute('data-id')),
            supplier_name: target.getAttribute('data-name') || ''
        };

        if (!selectedSupplier.id) {
            return;
        }

        setSelectedSupplier(selectedSupplier);
    });

    if (quickSupplierForm && quickSupplierName && quickSupplierError) {
        quickSupplierForm.addEventListener('submit', function (event) {
            event.preventDefault();
            quickSupplierError.classList.add('d-none');
            quickSupplierError.textContent = '';

            const supplierName = quickSupplierName.value.trim();
            if (!supplierName) {
                quickSupplierError.textContent = 'Debes ingresar el nombre del proveedor.';
                quickSupplierError.classList.remove('d-none');
                return;
            }

            fetch(buildEndpoint('admin-fit/bill/supplier-quick-create'), {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Accept: 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify({ supplier_name: supplierName })
            })
                .then(async (response) => {
                    const data = await response.json().catch(() => ({}));
                    if (!response.ok || data.success === false || !data.data) {
                        throw new Error(data.message || 'No se pudo crear el proveedor');
                    }

                    setSelectedSupplier(data.data);
                    quickSupplierName.value = '';

                    const modalElement = document.getElementById('quickSupplierModal');
                    if (modalElement && window.bootstrap?.Modal) {
                        const currentModal = window.bootstrap.Modal.getInstance(modalElement);
                        if (currentModal) {
                            currentModal.hide();
                        }
                    }
                })
                .catch((error) => {
                    quickSupplierError.textContent = error.message || 'Error creando proveedor';
                    quickSupplierError.classList.remove('d-none');
                });
        });
    }
}

function initBillCreatePanel() {
    const detailsTableBody = document.querySelector('#billDetailsTable tbody');
    const detailsInput = document.getElementById('bill_details_json');

    if (!detailsTableBody || !detailsInput) {
        return;
    }

    const productSearchInput = document.getElementById('product_search');
    const productSearchBtn = document.getElementById('productSearchBtn');
    const productResults = document.getElementById('productResults');
    const selectedProductLabel = document.getElementById('selectedProductLabel');
    const productQuantityInput = document.getElementById('product_quantity');
    const addBillDetailBtn = document.getElementById('addBillDetailBtn');

    const rateInput = document.getElementById('amount_rate_input');
    const hiddenRateInput = document.getElementById('amount_rate');
    const statusInput = document.getElementById('status');

    const totalInput = document.getElementById('total');
    const debtInput = document.getElementById('debt');
    const auxTotalInput = document.getElementById('aux_total');
    const auxDebtInput = document.getElementById('aux_debt');

    const summaryTotal = document.getElementById('summaryTotal');
    const summaryDebt = document.getElementById('summaryDebt');
    const summaryAuxTotal = document.getElementById('summaryAuxTotal');
    const summaryAuxDebt = document.getElementById('summaryAuxDebt');

    const quickProductForm = document.getElementById('quickProductForm');
    const quickProductName = document.getElementById('quick_product_name');
    const quickProductPurchasePrice = document.getElementById('quick_product_purchase_price');
    const quickProductStock = document.getElementById('quick_product_stock');
    const quickProductDescription = document.getElementById('quick_product_description');
    const quickProductError = document.getElementById('quickProductError');

    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';

    let selectedProduct = null;
    let billDetails = parseInitialDetails(detailsInput.value);

    function parseInitialDetails(raw) {
        try {
            const parsed = JSON.parse(raw || '[]');
            if (!Array.isArray(parsed)) {
                return [];
            }

            return parsed
                .map((item) => ({
                    product_id: Number(item.product_id || 0),
                    product_name: String(item.product_name || 'Producto'),
                    quantity: Number(item.quantity || 0),
                    base_price: Number(item.base_price || 0)
                }))
                .filter((item) => item.product_id > 0 && item.quantity > 0);
        } catch {
            return [];
        }
    }

    function formatMoney(value) {
        return Number(value || 0).toFixed(2);
    }

    function getCurrentRate() {
        const rate = Number(rateInput?.value || hiddenRateInput?.value || 1);
        return rate > 0 ? rate : 1;
    }

    function updateHiddenInputs(auxTotal, total, auxDebt, debt) {
        detailsInput.value = JSON.stringify(billDetails.map((item) => ({
            product_id: item.product_id,
            quantity: item.quantity,
            base_price: item.base_price,
            product_name: item.product_name
        })));

        if (hiddenRateInput) {
            hiddenRateInput.value = String(getCurrentRate());
        }

        if (auxTotalInput) {
            auxTotalInput.value = formatMoney(auxTotal);
        }

        if (totalInput) {
            totalInput.value = formatMoney(total);
        }

        if (auxDebtInput) {
            auxDebtInput.value = formatMoney(auxDebt);
        }

        if (debtInput) {
            debtInput.value = formatMoney(debt);
        }
    }

    function renderDetails() {
        const rate = getCurrentRate();

        if (!billDetails.length) {
            detailsTableBody.innerHTML = '<tr><td colspan="6" class="text-center text-muted py-3">Agrega productos para comenzar</td></tr>';
        } else {
            detailsTableBody.innerHTML = billDetails.map((item) => {
                const lineAuxSubtotal = Number(item.base_price) * Number(item.quantity);
                const lineSubtotal = lineAuxSubtotal * rate;

                return `
                    <tr>
                        <td>${escapeHtml(item.product_name)}</td>
                        <td class="text-end">${formatMoney(item.base_price)}</td>
                        <td class="text-center">${item.quantity}</td>
                        <td class="text-end">${formatMoney(lineAuxSubtotal)}</td>
                        <td class="text-end">${formatMoney(lineSubtotal)}</td>
                        <td class="text-center">
                            <button type="button" class="btn btn-sm btn-outline-danger remove-detail-item" data-product-id="${item.product_id}">Quitar</button>
                        </td>
                    </tr>
                `;
            }).join('');
        }

        const auxTotal = billDetails.reduce((acc, item) => acc + Number(item.base_price) * Number(item.quantity), 0);
        const total = auxTotal * rate;
        const isPending = String(statusInput?.value || '').toLowerCase() === 'pendiente';
        const auxDebt = isPending ? auxTotal : 0;
        const debt = isPending ? total : 0;

        if (summaryAuxTotal) {
            summaryAuxTotal.textContent = formatMoney(auxTotal);
        }

        if (summaryTotal) {
            summaryTotal.textContent = formatMoney(total);
        }

        if (summaryAuxDebt) {
            summaryAuxDebt.textContent = formatMoney(auxDebt);
        }

        if (summaryDebt) {
            summaryDebt.textContent = formatMoney(debt);
        }

        updateHiddenInputs(auxTotal, total, auxDebt, debt);
    }

    function escapeHtml(text) {
        return String(text)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function renderProductResults(items) {
        if (!productResults) {
            return;
        }

        if (!Array.isArray(items) || items.length === 0) {
            productResults.classList.remove('d-none');
            productResults.innerHTML = '<div class="list-group-item text-muted">Sin resultados</div>';
            return;
        }

        productResults.innerHTML = items.map((item) => {
            const price = Number(item.purchase_price || 0);
            const stock = Number(item.current_stock || 0);

            return `
                <button
                    type="button"
                    class="list-group-item list-group-item-action product-result-item"
                    data-id="${item.id}"
                    data-name="${escapeHtml(item.product_name)}"
                    data-price="${price}"
                >
                    <div class="d-flex justify-content-between">
                        <span>${escapeHtml(item.product_name)}</span>
                        <small class="text-muted">Base ${formatMoney(price)} | Stock ${stock}</small>
                    </div>
                </button>
            `;
        }).join('');

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

    function fetchProducts(query) {
        const searchTerm = String(query || '').trim();

        if (!searchTerm) {
            if (productResults) {
                productResults.classList.add('d-none');
                productResults.innerHTML = '';
            }
            return;
        }

        fetch(buildEndpoint(`admin-fit/bill/product-search?q=${encodeURIComponent(searchTerm)}`), {
            method: 'GET',
            headers: {
                Accept: 'application/json'
            }
        })
            .then(async (response) => {
                const data = await response.json().catch(() => ({}));
                if (!response.ok || data.success === false) {
                    throw new Error(data.message || 'No se pudo buscar productos');
                }
                renderProductResults(data.data || []);
            })
            .catch((error) => {
                if (productResults) {
                    productResults.classList.remove('d-none');
                    productResults.innerHTML = `<div class="list-group-item text-danger">${error.message || 'Error buscando productos'}</div>`;
                }
            });
    }

    if (productSearchInput) {
        let productSearchDebounce = null;
        productSearchInput.addEventListener('input', function () {
            if (productSearchDebounce) {
                clearTimeout(productSearchDebounce);
            }

            productSearchDebounce = setTimeout(() => {
                fetchProducts(productSearchInput.value);
            }, 250);
        });
    }

    if (productSearchBtn && productSearchInput) {
        productSearchBtn.addEventListener('click', function () {
            fetchProducts(productSearchInput.value);
        });
    }

    if (productResults && selectedProductLabel) {
        productResults.addEventListener('click', function (event) {
            const target = event.target.closest('.product-result-item');
            if (!target) {
                return;
            }

            selectedProduct = {
                product_id: Number(target.getAttribute('data-id')),
                product_name: target.getAttribute('data-name') || '',
                base_price: Number(target.getAttribute('data-price') || 0)
            };

            selectedProductLabel.textContent = `Producto seleccionado: ${selectedProduct.product_name}`;
            productResults.classList.add('d-none');
        });
    }

    if (addBillDetailBtn) {
        addBillDetailBtn.addEventListener('click', function () {
            if (!selectedProduct || !selectedProduct.product_id) {
                alert('Selecciona un producto antes de agregar.');
                return;
            }

            const quantity = Number(productQuantityInput?.value || 0);
            if (quantity <= 0) {
                alert('La cantidad debe ser mayor a cero.');
                return;
            }

            const existingIndex = billDetails.findIndex((item) => item.product_id === selectedProduct.product_id);
            if (existingIndex >= 0) {
                billDetails[existingIndex].quantity += quantity;
            } else {
                billDetails.push({
                    product_id: selectedProduct.product_id,
                    product_name: selectedProduct.product_name,
                    base_price: selectedProduct.base_price,
                    quantity
                });
            }

            if (productQuantityInput) {
                productQuantityInput.value = '1';
            }

            renderDetails();
        });
    }

    detailsTableBody.addEventListener('click', function (event) {
        const target = event.target.closest('.remove-detail-item');
        if (!target) {
            return;
        }

        const productId = Number(target.getAttribute('data-product-id'));
        billDetails = billDetails.filter((item) => item.product_id !== productId);
        renderDetails();
    });

    if (rateInput) {
        rateInput.addEventListener('input', function () {
            renderDetails();
        });
    }

    if (statusInput) {
        statusInput.addEventListener('change', function () {
            renderDetails();
        });
    }

    if (quickProductForm && quickProductName && quickProductPurchasePrice && quickProductStock && quickProductDescription && quickProductError) {
        quickProductForm.addEventListener('submit', function (event) {
            event.preventDefault();
            quickProductError.classList.add('d-none');
            quickProductError.textContent = '';

            const payload = {
                product_name: quickProductName.value.trim(),
                purchase_price: Number(quickProductPurchasePrice.value || 0),
                current_stock: Number(quickProductStock.value || 0),
                description: quickProductDescription.value.trim() || null
            };

            if (!payload.product_name || payload.purchase_price < 0) {
                quickProductError.textContent = 'Completa nombre y precio de compra válido.';
                quickProductError.classList.remove('d-none');
                return;
            }

            fetch(buildEndpoint('admin-fit/bill/product-quick-create'), {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Accept: 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify(payload)
            })
                .then(async (response) => {
                    const data = await response.json().catch(() => ({}));
                    if (!response.ok || data.success === false || !data.data) {
                        throw new Error(data.message || 'No se pudo crear el producto');
                    }

                    selectedProduct = {
                        product_id: Number(data.data.id),
                        product_name: String(data.data.product_name || ''),
                        base_price: Number(data.data.purchase_price || 0)
                    };

                    if (selectedProductLabel) {
                        selectedProductLabel.textContent = `Producto seleccionado: ${selectedProduct.product_name}`;
                    }

                    quickProductForm.reset();

                    const modalElement = document.getElementById('quickProductModal');
                    if (modalElement && window.bootstrap?.Modal) {
                        const currentModal = window.bootstrap.Modal.getInstance(modalElement);
                        if (currentModal) {
                            currentModal.hide();
                        }
                    }
                })
                .catch((error) => {
                    quickProductError.textContent = error.message || 'Error creando producto';
                    quickProductError.classList.remove('d-none');
                });
        });
    }

    const billForm = document.getElementById('billForm');
    if (billForm) {
        billForm.addEventListener('submit', function (event) {
            if (!billDetails.length) {
                event.preventDefault();
                alert('Debes agregar al menos un producto al detalle.');
                return;
            }

            renderDetails();
        });
    }

    renderDetails();
}
