@using Microsoft.AspNetCore.Mvc.Localization
@using Berufsschule_HAM.Models
@model HomeIndexViewModel
@inject IViewLocalizer T
@inject IConfiguration Configuration
@{
    ViewData["Title"] = T["Inventory"];
    string barcodeType = Configuration["BarcodeType"] ?? "EAN13";
}
<link href="https://cdn.jsdelivr.net/npm/tom-select/dist/css/tom-select.bootstrap5.min.css" rel="preload" as="style" onload="this.onload=null;this.rel='stylesheet'"/>
<script src="/js/tom-select.min.js" defer></script>

<partial name="_BatchButton"/>

<div class="container py-4">
    <h2 class="mb-3">@T["Inventory"]</h2>

    <div class="row g-3">
        <div class="col-md-3 text-center">
            <input type="text" id="barcodeInput" class="form-control mt-3" placeholder="@T["Asset ID"]" />
            <button id="enterAssetIdManuallyButton" class="btn btn-secondary mt-3">@T["Enter asset ID manually"]</button>
            <div id="reader" style="display:none" class="mt-3"></div>
            <button id="scanBarcodeButton" class="btn btn-primary mt-3">@T["Scan barcode"]</button>
            @if (User.IsInRole("CanManageAssets"))
            {
                <a asp-controller="Home" asp-action="Assets" asp-route-CreateModal="true" class="mt-3" style="display: block;">@T["Add a new asset"]</a>
            }
        </div>
    </div>
</div>

<!-- Detail view Modal -->
<div class="modal fade" id="viewAssetModal" tabindex="-1" aria-labelledby="viewAssetModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h3 class="modal-title text-dark" id="viewAssetModalLabel">@T["Asset Details"]</h3>
                <button type="button" class="btn-close btn-close-white" style="filter: invert(0);" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">
                <div id="viewAssetContent">
                    <p class="text-center text-muted">@T["Waiting for barcode scan..."]</p>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">@T["Abort"]</button>
                <button type="button" class="btn btn-warning" data-bs-dismiss="modal">@T["Update information"]</button>
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">@T["Information is correct"]</button>
            </div>
        </div>
    </div>
</div>

<style>
    .asset-row > td:not(:last-child) {
        cursor: pointer;
    }
    .asset-row > td {    
        transition: 0.1s ease;
    }
    .asset-row:has(td:not(:last-child):hover) > td {
        background-color: #17a2b8;
    }
</style>


@section Scripts {
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.6/dist/JsBarcode.all.min.js" defer></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html5-qrcode/2.3.8/html5-qrcode.min.js"></script>

    <script defer>

        async function onScanSuccess(decodedText, decodedResult) {
            const rawDecoded = decodedText;
            const BARCODE_TYPE = "@barcodeType";
            switch (BARCODE_TYPE.toUpperCase()) {
                case "EAN13":
                    decodedText = decodedText.slice(0,-1);
                    break;
                case "EAN8":
                    decodedText = decodedText.slice(0,-1);
                    break;
                case "UPC":
                    decodedText = decodedText.slice(0,-1);
                    break;
                case "ITF14":
                    decodedText = decodedText.slice(0,-1);
                    break;
                case "MSI10":
                    decodedText = decodedText.slice(0,-1);
                    break;
                case "MSI11":
                    decodedText = decodedText.slice(0,-1);
                    break;
                case "MSI1010":
                    decodedText = decodedText.slice(0,-2);
                    break;
                case "MSI1110":
                    decodedText = decodedText.slice(0,-1);
                    break;
            }
            decodedText = decodedText.replace(/^0+/, '');
            console.log(`Code matched = ${decodedText}`, decodedResult);
            document.getElementById("barcodeInput").value = decodedText;

            if (decodedResult != null)
            {
                html5QrCode.stop().then(() => console.log("Scanner stopped.")).catch(console.error);
            }

            // Now show the asset modal
            const viewModal = document.getElementById('viewAssetModal');
            const viewContent = document.getElementById('viewAssetContent');
            const modal = new bootstrap.Modal(viewModal);

            viewContent.innerHTML = '<p class="text-center text-muted">@T["Loading..."]</p>';

            try {
                const response = await fetch(`/Assets/Get?cn=${decodedText}`);
                const json = await response.json();
                const asset = json.assetsModel;

                if (!asset) {
                    const input = document.getElementById("barcodeInput");
                    input.classList.add("is-invalid");
                    showToast('@T["Asset not found."]', 'danger');
                    return;
                }
                modal.show();

                const html = `
                    <div class="row g-3">
                        <h4 class="fw-bold">@T["Barcode"]</h4>
                        <div class="col-md-6">
                            <svg id="@barcodeType" class="form-control" name="Barcode" />
                        </div>
                        <div class="col-md-6">
                            <button id="downloadBtn" class="form-control my-2 btn btn-primary">@T["Download Barcode"]</button>
                            <button id="printBtn" class="form-control my-2 btn btn-primary">@T["Add Barcode to print batch"]</button>
                        </div>
                    </div>
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label" for="detailName">@T["Name"]</label>
                            <input type="text" class="form-control" id="detailName" name="Name" value="${asset.Name || ''}" disabled />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="detailLocation">@T["Location"]</label>
                            <input type="text" class="form-control" id="detailLocation" name="Location" value="${asset.Location || ''}" disabled />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="detailOwner">@T["Owner"]</label>
                            <input type="text" class="form-control" id="detailOwner" name="Owner" value="${asset.Owner || ''}" disabled />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="detailSerialNumber">@T["Serial Number"]</label>
                            <input type="text" class="form-control" id="detailSerialNumber" name="SerialNumber" value="${asset.SerialNumber || ''}" disabled />
                        </div>
                    </div>
                    <hr class="my-3" />
                    <div class="row g-3">
                        <h4 class="fw-bold">@T["Description"]</h4>
                        <div class="col-md-6">
                            <label class="form-label" for="detailType">@T["Type"]</label>
                            <input type="text" class="form-control" id="detailType" name="Description.Type" value="${asset.Description?.Type || ''}" disabled />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="detailMake">@T["Make"]</label>
                            <input type="text" class="form-control" id="detailMake" name="Description.Make" value="${asset.Description?.Make || ''}" disabled />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="detailModel">@T["Model"]</label>
                            <input type="text" class="form-control" id="detailModel" name="Description.Model" value="${asset.Description?.Model || ''}" disabled />
                        </div>
                    </div>
                    ${asset.Description?.Attributes ? `
                    <hr class="my-3" />
                    <div class="row g-3">
                        <h4 class="fw-bold">@T["Attributes"]</h4>
                            ${Object.entries(asset.Description.Attributes)
                                .map(([k,v]) => `
                                <div class="d-flex gap-2 align-items-center attribute-row">
                                    <input type="text" class="form-control w-50" placeholder="@T["Attribute name"]" aria-label="@T["Attribute name"]" data-attr-name disabled value="${k}" />:
                                    <input type="text" class="form-control" placeholder="@T["Attribute value"]" aria-label="@T["Attribute value"]" data-attr-value disabled value="${v}" />
                                </div>`)
                                .join('')}
                        </div>` : ''}
                                
                    ${asset.Description?.Purchase ? `
                    <hr class="my-3" />
                    <div class="row g-3">
                        <h4 class="fw-bold">@T["Purchase Information"]</h4>
                        <div class="col-md-6">
                            <label class="form-label" for="detailPurchaseDate">@T["Purchase Date"]</label>
                            <input type="date" class="form-control" id="detailPurchaseDate" name="Description.Purchase.PurchaseDate" value="${asset.Description.Purchase.PurchaseDate || ''}" disabled />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="detailPurchaseValue">@T["Purchase Value"]</label>
                            <input type="text" class="form-control" id="detailPurchaseValue" name="Description.Purchase.PurchaseValue" value="${asset.Description.Purchase.PurchaseValue || ''}" disabled />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="detailPurchaseAt">@T["Purchased At"]</label>
                            <input type="text" class="form-control" id="detailPurchaseAt" name="Description.Purchase.PurchaseAt" value="${asset.Description.Purchase.PurchaseAt || ''}" disabled />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="detailPurchaseBy">@T["Purchased By"]</label>
                            <input type="text" class="form-control" id="detailPurchaseBy" name="Description.Purchase.PurchaseBy" value="${asset.Description.Purchase.PurchaseBy || ''}" disabled />
                        </div>
                    </div>` : ''}
                </div>`;

                viewContent.innerHTML = html;
                console.log(rawDecoded);
                JsBarcode("#@barcodeType", getBarcodeValue("@barcodeType", decodedText), {
                    format: "@barcodeType",
                    lineColor: "#000",
                    width: 2,
                    height: 80,
                    displayValue: true
                });

                document.getElementById("downloadBtn").addEventListener("click", () => downloadBarcode("@barcodeType", decodedText));
                document.getElementById("printBtn").addEventListener("click", () => {
                    addAssetIdToBatch(asset.Cn);
                    showToast("@T["Successfully added barcode to print batch"]", "success");
                    bootstrap.Modal.getInstance('#viewAssetModal').hide();
                });

            } catch (err) {
                console.error(err);
                viewContent.innerHTML = `<p class="text-danger text-center">@T["Error loading asset details"]</p>`;
            }
        }

        function onScanError(errorMessage) {
            console.warn(errorMessage);
        }

        let html5QrCode;

        const assetIdManuallyButton = document.querySelector('#enterAssetIdManuallyButton');
        if (assetIdManuallyButton) {
            assetIdManuallyButton.addEventListener('click', async () => {
                if (html5QrCode) {
                    try {
                        await html5QrCode.stop();
                        document.getElementById("reader").style.display = "none";
                    } catch (err) {
                        console.warn("Could not stop scanner:", err);
                    }
                }
                await onScanSuccess(document.getElementById("barcodeInput").value, null);
            });
        }
        const scanBarcodeButton = document.querySelector('#scanBarcodeButton');
        if (scanBarcodeButton) {
            scanBarcodeButton.addEventListener('click', () => {
                let reader = document.querySelector('#reader');
                reader.style.display = ""
                
                html5QrCode = new Html5Qrcode("reader");
                html5QrCode.start(
                    { facingMode: "environment" },
                    { fps: 10, qrbox: { width: 300, height: 150 } },
                    onScanSuccess,
                    onScanError
                );
            });
        }

        // Handle "Update information" button click in viewAssetModal
        const updateBtn = document.querySelector('#viewAssetModal .btn.btn-warning');
        if (updateBtn) {
            updateBtn.addEventListener('click', () => {
                const viewModalEl = document.getElementById('viewAssetModal');
                const viewModal = bootstrap.Modal.getInstance(viewModalEl);

                // Hide current modal
                viewModal.hide();

                // Wait a bit to ensure fade animation finishes
                setTimeout(() => {
                    const updateModalEl = document.getElementById('updateAssetModal');
                    const updateModal = new bootstrap.Modal(updateModalEl);

                    // If you have the scanned asset ID, pass it as data-asset-id for the next modal
                    const scannedId = document.getElementById("barcodeInput")?.value || "";
                    if (scannedId) {
                        updateModalEl.setAttribute('data-asset-id', scannedId);
                    }

                    // Show the update modal
                    updateModal.show();
                }, 400);
            });
        }

        const okBtn = document.querySelector('#viewAssetModal .btn.btn-primary');
        if (okBtn) {
            okBtn.addEventListener('click', (e) => {
                try {
                    let assetId = document.getElementById("barcodeInput").value;
                    const jsonData = {"Cn": assetId};
                    jsonData.UpdateInventory = true;
                    const response = fetch('/Assets/Update', {
                        method: 'PATCH',
                        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
                        body: JSON.stringify(jsonData)
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.success) {
                            showToast('@T["Asset inventorized successfully"]', 'success');
                        } else {
                            e.preventDefault();
                            showToast(result.reason || '@T["Error updating asset"]', 'danger');
                        }
                    });
                } catch (err) {
                    console.error(err);
                    showToast('@T["Error contacting server"]', 'danger');
                }
            });
        }

        document.getElementById("barcodeInput").addEventListener("input", e => {
            e.target.classList.remove("is-invalid");
        });

    </script>
}


<div class="modal fade" id="updateAssetModal" tabindex="-1" aria-labelledby="updateAssetModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-warning text-dark">
                <h3 class="modal-title" id="updateAssetModalLabel">@T["Update Asset"]</h3>
                <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(0);" aria-label="Close"></button>
            </div>

            <form id="updateAssetForm">
                <div class="modal-body">
                    <div class="row g-3">
                        <!-- Same fields as in Create -->
                        <div class="col-md-6">
                            <label class="form-label" for="updateName">@T["Name"]</label>
                            <input type="text" id="updateName" class="form-control" name="Name" />
                        </div>

                        <div class="col-md-6">
                            <label class="form-label" for="updateLocationSelect">@T["Location"]</label>
                            <select class="form-select" name="Location" aria-label="@T["Location"]" id="updateLocationSelect">
                                <option value="">@T["Select location"]</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="updateUsersSelect">@T["Owner"]</label>
                            <select class="form-select" name="Owner" aria-label="@T["Owner"]" id="updateUsersSelect">
                                <option value="">@T["Select owner"]</option>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label" for="updateSerialNumber">@T["Serial Number"]</label>
                            <input type="text" class="form-control" id="updateSerialNumber" name="SerialNumber" />
                        </div>

                        <hr class="my-3" />

                        <h4 class="fw-bold">@T["Description"]</h4>
                        <div class="col-md-6">
                            <label class="form-label" for="updateType">@T["Type"]</label>
                            <input type="text" class="form-control" id="updateType" name="Description.Type" />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="updateMake">@T["Make"]</label>
                            <input type="text" class="form-control" id="updateMake" name="Description.Make" />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="updateModel">@T["Model"]</label>
                            <input type="text" class="form-control" id="updateModel" name="Description.Model" />
                        </div>

                        <div class="col-12 mt-3">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <h4 class="fw-bold mb-0">@T["Attributes"]</h4>
                            </div>
                            <div id="updateAttributesContainer" class="d-flex flex-column gap-2"></div>
                            <button type="button" class="btn btn-sm btn-primary mt-3" id="updateAddAttributeBtn">
                                @T["Add Attribute"]
                            </button>
                        </div>

                        <hr class="my-3" />

                        <h4 class="fw-bold">@T["Purchase Information"]</h4>
                        <div class="col-md-6">
                            <label class="form-label" for="updatePurchaseDate">@T["Purchase Date"]</label>
                            <input type="date" class="form-control" id="updatePurchaseDate" name="Description.Purchase.PurchaseDate" />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="updatePurchaseValue">@T["Purchase Value"]</label>
                            <input type="text" class="form-control" id="updatePurchaseValue" name="Description.Purchase.PurchaseValue" />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="updatePurchaseAt">@T["Purchased At"]</label>
                            <input type="text" class="form-control" id="updatePurchaseAt" name="Description.Purchase.PurchaseAt" />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="updatePurchaseBy">@T["Purchased By"]</label>
                            <input type="text" class="form-control" id="updatePurchaseBy" name="Description.Purchase.PurchaseBy" />
                        </div>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">@T["Cancel"]</button>
                    <button type="submit" class="btn btn-warning">@T["Save Changes"]</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const updateButtons = document.querySelectorAll('.btn-update');
    const updateModal = document.getElementById('updateAssetModal');
    const updateForm = document.getElementById('updateAssetForm');
    const updateAttributesContainer = document.getElementById('updateAttributesContainer');
    const addAttrBtn = document.getElementById('updateAddAttributeBtn');
    let assetId = null;

    addAttrBtn.addEventListener('click', () => {
        const row = document.createElement('div');
        row.className = 'd-flex gap-2 align-items-center attribute-row';
        row.innerHTML = `
            <input type="text" class="form-control" aria-label="@T["Attribute name"]" placeholder="@T["Attribute name"]" data-attr-name />
            <input type="text" class="form-control" aria-label="@T["Attribute value"]" placeholder="@T["Attribute value"]" data-attr-value />
            <button type="button" class="btn btn-danger btn-sm btn-remove-attribute">@T["Remove"]</button>
        `;
        updateAttributesContainer.appendChild(row);
    });

    updateAttributesContainer.addEventListener('click', e => {
        if (e.target.classList.contains('btn-remove-attribute')) {
            e.target.closest('.attribute-row').remove();
        }
    });

    updateModal.addEventListener('show.bs.modal', async event => {
        const modal = event.target;
        const button = event.relatedTarget;
        assetId = modal.getAttribute('data-asset-id');

        updateAttributesContainer.innerHTML = '';
        updateForm.reset();

        try {
            const response = await fetch(`/Assets/Get?cn=${assetId}`);
            const responseJson = await response.json();
            const asset = responseJson.assetsModel;

            const locationSelect = updateForm.querySelector('#updateLocationSelect');
            const usersSelect = updateForm.querySelector('#updateUsersSelect');
            await Promise.all([
                loadLocationsIntoSelect(locationSelect, asset.Location),
                loadUsersIntoSelect(usersSelect, asset.Owner)
            ]);

            for (const [key, value] of Object.entries(asset)) {
                const input = updateForm.querySelector(`[name="${key}"]`);
                if (input) input.value = value;
            }

            // Handle nested description fields
            if (asset.Description) {
                for (const [descKey, descVal] of Object.entries(asset.Description)) {
                    const field = updateForm.querySelector(`[name="Description.${descKey}"]`);
                    if (field && typeof descVal === 'string') field.value = descVal;
                }

                // Attributes
                if (asset.Description.Attributes) {
                    for (const [attrName, attrValue] of Object.entries(asset.Description.Attributes)) {
                        const row = document.createElement('div');
                        row.className = 'd-flex gap-2 align-items-center attribute-row';
                        row.innerHTML = `
                            <input type="text" class="form-control" aria-label="@T["Attribute name"]" value="${attrName}" data-attr-name />
                            <input type="text" class="form-control" aria-label="@T["Attribute value"]" value="${attrValue}" data-attr-value />
                            <button type="button" class="btn btn-danger btn-sm btn-remove-attribute">@T["Remove"]</button>
                        `;
                        updateAttributesContainer.appendChild(row);
                    }
                }

                // Purchase info
                if (asset.Description.Purchase) {
                    for (const [pKey, pValue] of Object.entries(asset.Description.Purchase)) {
                        const field = updateForm.querySelector(`[name="Description.Purchase.${pKey}"]`);
                        if (field) field.value = pValue;
                    }
                }
            }
        } catch (err) {
            console.error(err);
            showToast('@T["Error loading asset data"]', 'danger');
        }
    });

    updateForm.addEventListener('submit', async e => {
        e.preventDefault();

        const formData = new FormData(updateForm);
        const jsonData = {"Cn": assetId};
        for (const [key, value] of formData.entries()) {
            if (!value) continue;
            const keys = key.split('.');
            let target = jsonData;
            for (let i = 0; i < keys.length - 1; i++) {
                target[keys[i]] = target[keys[i]] || {};
                target = target[keys[i]];
            }
            target[keys[keys.length - 1]] = value;
        }

        const attributes = {};
        document.querySelectorAll('#updateAttributesContainer .attribute-row').forEach(row => {
            const name = row.querySelector('[data-attr-name]').value.trim();
            const value = row.querySelector('[data-attr-value]').value.trim();
            if (name) attributes[name] = value;
        });

        if (Object.keys(attributes).length > 0) {
            jsonData.Description = jsonData.Description || {};
            jsonData.Description.Attributes = attributes;
        }
        jsonData.UpdateInventory = true;

        try {
            const response = await fetch('/Assets/Update', {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
                body: JSON.stringify(jsonData)
            });
            const result = await response.json();

            if (result.success) {
                bootstrap.Modal.getInstance(updateModal).hide();
                showToast('@T["Asset updated successfully"]', 'success');

                // Optionally refresh the row
                const row = [...document.querySelectorAll('tr')]
                    .find(r => r.querySelector(`[data-asset-id="${jsonData.Cn}"]`));
                if (row) {
                    row.children[0].textContent = jsonData.Owner || '';
                    row.children[1].textContent = jsonData.Cn || '';
                    row.children[2].textContent = jsonData.Name || '';
                    row.children[3].textContent = jsonData.Location || '';
                }
            } else {
                showToast(result.reason || '@T["Error updating asset"]', 'danger');
            }
        } catch (err) {
            console.error(err);
            showToast('@T["Error contacting server"]', 'danger');
        }
    });
});
</script>

<!-- TomSelect dropdowns -->
<script>
    // Locations dropdowns
    document.addEventListener('DOMContentLoaded', () => {
        const updateLocationSelect = document.getElementById('updateLocationSelect');

        async function initLocationSelect(selectElement) {
            if (!selectElement) return;
            await loadLocationsIntoSelect(selectElement);
            new TomSelect(selectElement, {
                plugins: ['clear_button'],
                create: false,
                sortField: { field: 'text', direction: 'asc' },
                placeholder: '@T["Select location"]',
                maxOptions: 500, // avoid performance hit if there are many
                render: {
                    no_results: function(data, escape) {
                        return `<div class="no-results">@T["No locations found"]</div>`;
                    }
                }
            });
        }

        initLocationSelect(updateLocationSelect);
        
        // Users dropdowns
        const updateUsersSelect = document.getElementById('updateUsersSelect');

        async function initUsersSelect(selectElement) {
            if (!selectElement) return;
            await loadUsersIntoSelect(selectElement);
            new TomSelect(selectElement, {
                plugins: ['clear_button'],
                create: false,
                sortField: { field: 'text', direction: 'asc' },
                placeholder: '@T["Select user"]',
                maxOptions: 500, // avoid performance hit if there are many
                render: {
                    no_results: function(data, escape) {
                        return `<div class="no-results">@T["No users found"]</div>`;
                    }
                }
            });
        }

        initUsersSelect(updateUsersSelect);
    });

</script>



<partial name="_Batch"/>