@page
@model ConfigurationPannel.Pages.ConfigureModel
@{
    ViewData["Title"] = "Printer Configuration";
}

<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Printer Configuration</h2>
        <div>
            <button type="button" class="btn btn-secondary" onclick="discoverPrinters()">
                <span id="discover-spinner" class="spinner-border spinner-border-sm d-none"></span>
                Discover Printers
            </button>
            <a asp-page="/Logout" class="btn btn-outline-secondary">Logout</a>
        </div>
    </div>

    <div id="discovery-status" class="alert alert-info d-none">
        Discovering printers...
    </div>

    <div id="discovered-printers" class="mb-4">
        <h5>Discovered Printers: <span id="printer-count">@Model.DiscoveredPrinters.Count</span></h5>
        <ul id="printer-list" class="list-group">
            @foreach (var printer in Model.DiscoveredPrinters)
            {
                <li class="list-group-item">@printer.IPAddress </li>
            }
        </ul>
    </div>

    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h4>Logo Management</h4>
            <button type="button" class="btn btn-sm btn-warning" onclick="document.getElementById('cleanLogosForm').submit()">
                Clean Unused Logos
            </button>
        </div>
        <div class="card-body">
            <form method="post" asp-page-handler="UploadLogo" enctype="multipart/form-data" class="d-flex gap-2 align-items-center">
                <input type="file" name="UploadedLogo" accept=".png,.jpg,.jpeg,.gif,.bmp" class="form-control" style="max-width: 400px;" />
                <button type="submit" class="btn btn-primary">Upload Logo</button>
            </form>
            <small class="text-muted">Supported formats: PNG, JPG, JPEG, GIF, BMP</small>

            @if (Model.AvailableLogos.Any())
            {
                <div class="mt-3">
                    <strong>Available logos (@Model.AvailableLogos.Count):</strong>
                    <div class="d-flex flex-wrap gap-2 mt-2">
                        @foreach (var logo in Model.AvailableLogos)
                        {
                            <div class="border p-2 text-center" style="width: 120px;">
                                <a href="/logos/@logo" target="_blank">
                                    <img src="/logos/@logo" alt="@logo" style="max-width: 100px; max-height: 80px;" class="d-block mx-auto" />
                                </a>
                                <small class="text-muted d-block mt-1" style="font-size: 10px; word-break: break-all;">@logo</small>
                            </div>
                        }
                    </div>
                </div>
            }
        </div>
    </div>

    <!-- Hidden form for cleaning logos -->
    <form id="cleanLogosForm" method="post" asp-page-handler="CleanLogos" style="display: none;"></form>

    <form method="post" asp-page-handler="Save">
        <div class="card">
            <div class="card-header">
                <h4>Work Area Assignments</h4>
            </div>
            <div class="card-body">
                @if (Model.WorkAreas == null || !Model.WorkAreas.Any())
                {
                    <div class="alert alert-warning">No work areas found. Check configuration.</div>
                }
                else
                {
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Work Area</th>
                                <th>Assigned Printer</th>
                                <th>Font Size</th>
                                <th>Logo</th>
                            </tr>
                        </thead>
                        <tbody>
                            @for (int i = 0; i < Model.WorkAreas.Count; i++)
                            {
                                var workArea = Model.WorkAreas[i];
                                var currentPrinter = Model.CurrentAssignments.TryGetValue(workArea.Id, out var assigned) ? assigned.Address : "";
                                var currentFontSize = Model.CurrentAssignments.TryGetValue(workArea.Id, out var cfg) ? cfg.FontSize : 1;

                                <tr>
                                    <td>
                                        <strong>@workArea.Name</strong>
                                        <input type="hidden" name="WorkAreaAssignments[@i].WorkAreaId" value="@workArea.Id" />
                                        <input type="hidden" name="WorkAreaAssignments[@i].WorkAreaName" value="@workArea.Name" />
                                    </td>
                                    <td>
                                        <select name="WorkAreaAssignments[@i].PrinterAddress"
                                                class="form-select printer-select"
                                                data-workarea="@workArea.Id">
                                            <option value="">None</option>
                                            @foreach (var printer in Model.DiscoveredPrinters)
                                            {
                                                var selected = currentPrinter == printer.IPAddress;
                                                <option value="@printer.IPAddress" selected="@selected">
                                                    @printer.IPAddress @(!string.IsNullOrEmpty(printer.ModelName) ? $"({printer.ModelName})" : "")
                                                </option>
                                            }
                                        </select>
                                    </td>
                                    <td>
                                        <input type="number"
                                               name="WorkAreaAssignments[@i].FontSize"
                                               class="form-control"
                                               min="1"
                                               max="4"
                                               value="@currentFontSize"
                                               style="width: 80px;" />
                                    </td>
                                    <td>
                                        @{
                                            var currentLogo = Model.CurrentAssignments.TryGetValue(workArea.Id, out var cfgLogo) ? cfgLogo.LogoFilename : "";
                                        }
                                        <select name="WorkAreaAssignments[@i].LogoFilename"
                                                id="logo-select-@i"
                                                class="form-select logo-select"
                                                onchange="updateLogoPreview(@i)"
                                                style="max-width: 200px;">
                                            <option value="">None</option>
                                            @foreach (var logo in Model.AvailableLogos)
                                            {
                                                var selected = currentLogo == logo;
                                                <option value="@logo" selected="@selected">@logo</option>
                                            }
                                        </select>

                                        <div id="logo-preview-@i" class="mt-2" style="display: none;">
                                            <a href="#" target="_blank" id="logo-link-@i">
                                                <img id="logo-img-@i" src="" alt="Logo preview" style="max-height: 100px; cursor: pointer;" />
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            }
                        </tbody>
                    </table>
                }
            </div>
        </div>

        <div class="mt-3">
            <button type="submit" class="btn btn-primary btn-lg">Save Configuration</button>
        </div>

        @if (!string.IsNullOrEmpty(Model.SuccessMessage))
        {
            <div class="alert alert-success mt-3">@Model.SuccessMessage</div>
        }
        @if (!string.IsNullOrEmpty(Model.ErrorMessage))
        {
            <div class="alert alert-danger mt-3">@Model.ErrorMessage</div>
        }
    </form>
</div>

@section Scripts {
    <script>
        async function discoverPrinters() {
            const button = document.querySelector('button[onclick="discoverPrinters()"]');
            const spinner = document.getElementById('discover-spinner');
            const status = document.getElementById('discovery-status');
            const printerList = document.getElementById('printer-list');
            const printerCount = document.getElementById('printer-count');

            button.disabled = true;
            spinner.classList.remove('d-none');
            status.classList.remove('d-none');
            printerList.innerHTML = '';
            printerCount.textContent = '0';

            try {
                const response = await fetch('/Configure?handler=Discover', {
                    method: 'POST',
                    headers: {
                        'RequestVerificationToken': document.querySelector('input[name="__RequestVerificationToken"]').value
                    }
                });

                const printers = await response.json();

                printerCount.textContent = printers.length;

                if (printers.length === 0) {
                    printerList.innerHTML = '<li class="list-group-item">No printers found</li>';
                } else {
                    // Update all select dropdowns with discovered printers
                    document.querySelectorAll('.printer-select').forEach(select => {
                        const currentValue = select.value;
                        // Keep "None" option
                        select.innerHTML = '<option value="">None</option>';

                        printers.forEach(printer => {
                            const option = document.createElement('option');
                            option.value = printer.ipAddress;
                            option.textContent = `${printer.ipAddress} ${printer.modelName ? '(' + printer.modelName + ')' : ''}`;
                            if (printer.ipAddress === currentValue) {
                                option.selected = true;
                            }
                            select.appendChild(option);
                        });
                    });

                    // Show discovered printers list
                    printers.forEach(printer => {
                        const li = document.createElement('li');
                        li.className = 'list-group-item';
                        li.textContent = `${printer.ipAddress}`;
                        printerList.appendChild(li);
                    });
                }
            } catch (error) {
                printerList.innerHTML = `<li class="list-group-item text-danger">Error: ${error.message}</li>`;
            } finally {
                button.disabled = false;
                spinner.classList.add('d-none');
                status.classList.add('d-none');
            }
        }

        function updateLogoPreview(index) {
            const select = document.getElementById(`logo-select-${index}`);
            const preview = document.getElementById(`logo-preview-${index}`);
            const img = document.getElementById(`logo-img-${index}`);
            const link = document.getElementById(`logo-link-${index}`);

            if (select.value) {
                const logoUrl = `/logos/${select.value}`;
                img.src = logoUrl;
                link.href = logoUrl;
                preview.style.display = 'block';
            } else {
                preview.style.display = 'none';
            }
        }

        // Initialize previews on page load
        document.addEventListener('DOMContentLoaded', function() {
            const selects = document.querySelectorAll('.logo-select');
            selects.forEach((select, index) => {
                if (select.value) {
                    updateLogoPreview(index);
                }
            });
        });
    </script>
}
