<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Buat Permintaan Barang</title>

    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">

    <style>
        body {
            margin: 0;
            font-family: 'Inter', sans-serif;
            background:
                radial-gradient(circle at top left, rgba(37, 99, 235, 0.07), transparent 24%),
                radial-gradient(circle at top right, rgba(15, 23, 42, 0.06), transparent 22%),
                linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
        }

        .app {
            display: flex;
            min-height: 100vh;
        }

        .content {
            flex: 1;
            padding: 32px;
            width: 100%;
        }

        .glass-card {
            background: rgba(255, 255, 255, 0.92);
            backdrop-filter: blur(10px);
        }

        @media (max-width:1024px) {
            .app {
                display: block;
            }

            .content {
                padding: 20px;
                padding-top: 80px;
            }
        }

        @media (max-width:640px) {
            .content {
                padding: 16px;
                padding-top: 80px;
            }
        }
    </style>
</head>

<body>
    <div class="app">
        @include('partials.sidebar')

        <main class="content">
            <div class="max-w-6xl mx-auto space-y-6">

                <div class="rounded-[28px] p-6 md:p-8 text-white shadow-xl overflow-hidden relative"
                    style="background: linear-gradient(135deg, #0f172a 0%, #1e3a8a 42%, #2563eb 100%);">
                    <div class="absolute top-0 right-0 w-72 h-72 bg-white/10 rounded-full blur-3xl -translate-y-16 translate-x-16"></div>
                    <div class="relative">
                        <div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/10 border border-white/10 text-xs font-semibold tracking-wide uppercase">
                            <i data-lucide="file-plus-2" class="w-3.5 h-3.5"></i>
                            Form Pengajuan
                        </div>

                        <h1 class="text-2xl md:text-4xl font-extrabold mt-4">Buat Permintaan Barang</h1>
                        <p class="text-blue-100/90 mt-3 text-sm md:text-base max-w-3xl leading-relaxed">
                            Ajukan kebutuhan barang operasional dengan data yang lengkap agar proses verifikasi dan realisasi dari sekretariat lebih cepat dan jelas.
                        </p>
                    </div>
                </div>

                <form action="{{ route('item-requests.store') }}" method="POST" class="grid grid-cols-1 xl:grid-cols-3 gap-6">
                    @csrf

                    <div class="xl:col-span-2">
                        <div class="glass-card border border-slate-200 rounded-[28px] shadow-xl overflow-hidden">
                            <div class="px-6 py-5 border-b border-slate-200 bg-gradient-to-r from-white to-slate-50">
                                <h2 class="text-xl font-bold text-slate-900">Form Permintaan Barang</h2>
                                <p class="text-sm text-slate-500 mt-1">Lengkapi informasi barang, jumlah, tanggal, dan keperluan penggunaan.</p>
                            </div>

                            <div class="p-6 grid grid-cols-1 md:grid-cols-2 gap-5">
                                <div class="md:col-span-2">
                                    <label class="block text-sm font-semibold text-slate-700 mb-2">Nama Barang</label>
                                    <select name="request_item_id" id="request_item_id"
                                        class="w-full rounded-2xl border border-slate-300 bg-white px-4 py-3 text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        required>
                                        <option value="">-- Pilih Barang --</option>
                                        @foreach($items as $item)
                                        <option
                                            value="{{ $item->id }}"
                                            data-unit="{{ $item->unit }}"
                                            data-image="{{ $item->image_url }}"
                                            data-stock="{{ $item->stock }}"
                                            data-description="{{ $item->description }}"
                                            {{ old('request_item_id') == $item->id ? 'selected' : '' }}>
                                            {{ $item->display_name }}{{ (float) $item->stock <= 0 ? ' - Stok habis' : '' }}
                                        </option>
                                        @endforeach
                                    </select>
                                    @error('request_item_id')
                                    <p class="text-rose-600 text-sm mt-2">{{ $message }}</p>
                                    @enderror
                                </div>

                                <div>
                                    <label class="block text-sm font-semibold text-slate-700 mb-2">Jumlah Barang</label>
                                    <div class="flex gap-3">
                                        <input
                                            type="number"
                                            id="quantity"
                                            name="quantity"
                                            value="{{ old('quantity') }}"
                                            class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            required>
                                        <div id="unit_badge" class="min-w-[100px] px-4 py-3 rounded-2xl bg-slate-100 text-slate-700 font-semibold text-center border border-slate-200">
                                            satuan
                                        </div>
                                    </div>
                                    <p id="quantity_hint" class="text-xs text-slate-500 mt-2">Pilih barang terlebih dahulu untuk menyesuaikan jumlah.</p>
                                    <p id="quantity_stock_warning" class="hidden text-rose-600 text-sm mt-2 font-medium"></p>
                                    @error('quantity')
                                    <p class="text-rose-600 text-sm mt-2">{{ $message }}</p>
                                    @enderror
                                </div>

                                <div>
                                    <label class="block text-sm font-semibold text-slate-700 mb-2">Stok Tersedia</label>
                                    <div id="stock_info" class="w-full rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 text-slate-700 font-medium">
                                        Pilih barang dulu
                                    </div>
                                </div>

                                <div id="stock_unavailable_notice" class="md:col-span-2 hidden rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm font-medium text-rose-700">
                                    Barang yang dipilih sedang habis. Form permintaan dinonaktifkan sampai stok tersedia kembali.
                                </div>

                                <div>
                                    <label class="block text-sm font-semibold text-slate-700 mb-2">Tanggal Pengajuan</label>
                                    <input
                                        type="date"
                                        id="request_date"
                                        name="request_date"
                                        value="{{ old('request_date', now()->format('Y-m-d')) }}"
                                        min="{{ now()->format('Y-m-d') }}"
                                        readonly
                                        class="w-full rounded-2xl border border-slate-300 bg-slate-50 px-4 py-3 text-slate-900 focus:outline-none"
                                        required>
                                    <p class="text-xs text-slate-500 mt-2">Otomatis menggunakan tanggal hari ini sebagai tanggal pengajuan.</p>
                                    @error('request_date')
                                    <p class="text-rose-600 text-sm mt-2">{{ $message }}</p>
                                    @enderror
                                </div>

                                <div>
                                    <label class="block text-sm font-semibold text-slate-700 mb-2">Target Realisasi</label>
                                    <input
                                        type="date"
                                        id="realization_date"
                                        name="realization_date"
                                        value="{{ old('realization_date') }}"
                                        class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        required>
                                    <p class="text-xs text-slate-500 mt-2">Isi kapan barang dibutuhkan oleh peminta. Tidak boleh lebih awal dari tanggal pengajuan.</p>
                                    @error('realization_date')
                                    <p class="text-rose-600 text-sm mt-2">{{ $message }}</p>
                                    @enderror
                                </div>

                                <div class="md:col-span-2">
                                    <label class="block text-sm font-semibold text-slate-700 mb-2">Keperluan / Keterangan</label>
                                    <textarea
                                        id="purpose"
                                        name="purpose"
                                        rows="4"
                                        placeholder="Contoh: Digunakan untuk perbaikan jaringan LAN ruangan rapat lantai 2..."
                                        class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                                        required>{{ old('purpose') }}</textarea>
                                    @error('purpose')
                                    <p class="text-rose-600 text-sm mt-2">{{ $message }}</p>
                                    @enderror
                                </div>
                            </div>

                            <div class="px-6 pb-6 flex flex-col sm:flex-row gap-3">
                                <button id="submit_request_button" type="submit"
                                    class="inline-flex justify-center items-center gap-2 px-6 py-3 rounded-2xl bg-blue-600 text-white font-semibold hover:bg-blue-700 transition shadow-sm">
                                    <i data-lucide="send" class="w-4 h-4"></i>
                                    <span id="submit_request_label">Kirim Permintaan</span>
                                </button>

                                <a href="{{ route('item-requests.index') }}"
                                    class="inline-flex justify-center items-center gap-2 px-6 py-3 rounded-2xl border border-slate-300 text-slate-700 font-semibold hover:bg-slate-50 transition">
                                    <i data-lucide="arrow-left" class="w-4 h-4"></i>
                                    Kembali
                                </a>
                            </div>
                        </div>
                    </div>

                    <div class="xl:col-span-1">
                        <div class="glass-card border border-slate-200 rounded-[28px] shadow-xl overflow-hidden sticky top-6">
                            <div class="px-6 py-5 border-b border-slate-200 bg-gradient-to-r from-white to-slate-50">
                                <h2 class="text-xl font-bold text-slate-900">Preview Barang</h2>
                                <p class="text-sm text-slate-500 mt-1">Informasi barang yang dipilih akan tampil otomatis di sini.</p>
                            </div>

                            <div class="p-6">
                                <img
                                    id="item_preview_image"
                                    src="https://via.placeholder.com/500x320?text=Preview+Barang"
                                    alt="Preview Barang"
                                    class="w-full h-72 object-cover rounded-2xl border border-slate-200 bg-slate-50 shadow-sm"
                                    onerror="this.onerror=null;this.src='https://via.placeholder.com/500x320?text=Gambar+Tidak+Valid';">

                                <div class="mt-4 space-y-3">
                                    <div class="rounded-2xl bg-slate-50 border border-slate-200 p-4">
                                        <div class="text-sm font-semibold text-slate-700 mb-2">Nama Barang</div>
                                        <div id="item_preview_name" class="text-sm text-slate-600">Belum dipilih</div>
                                    </div>

                                    <div class="rounded-2xl bg-blue-50 border border-blue-100 p-4">
                                        <div class="text-sm font-semibold text-blue-700 mb-2">Satuan Barang</div>
                                        <div id="item_preview_unit" class="text-sm text-blue-600">-</div>
                                    </div>

                                    <div class="rounded-2xl bg-emerald-50 border border-emerald-100 p-4">
                                        <div class="text-sm font-semibold text-emerald-700 mb-2">Stok Tersedia</div>
                                        <div id="item_preview_stock" class="text-sm text-emerald-600">-</div>
                                    </div>

                                    <div class="rounded-2xl bg-slate-50 border border-slate-200 p-4">
                                        <div class="text-sm font-semibold text-slate-700 mb-2">Deskripsi</div>
                                        <div id="item_preview_description" class="text-sm text-slate-600">Pilih barang terlebih dahulu untuk melihat deskripsi.</div>
                                    </div>

                                    <div class="rounded-2xl bg-amber-50 border border-amber-100 p-4">
                                        <div class="text-sm font-semibold text-amber-700 mb-2">Petunjuk Pengisian</div>
                                        <ul class="text-sm text-amber-600 space-y-1">
                                            <li>• Pilih barang yang ingin diajukan, lalu cek satuan dan stok yang tersedia.</li>
                                            <li>• Isi jumlah permintaan sesuai kebutuhan dan tidak melebihi stok yang tersedia.</li>
                                            <li>• Jika satuan barang adalah meter, jumlah boleh diisi dengan angka desimal.</li>
                                            <li>• Jika satuan barang adalah pcs atau unit, jumlah harus diisi dengan angka bulat.</li>
                                            <li>• Tanggal pengajuan diisi otomatis oleh sistem sesuai tanggal hari ini.</li>
                                            <li>• Isi target realisasi sesuai tanggal barang benar-benar dibutuhkan.</li>
                                            <li>• Jelaskan keperluan penggunaan barang agar proses verifikasi lebih mudah.</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </main>
    </div>

    <script>
        lucide.createIcons();

        document.addEventListener('DOMContentLoaded', function() {
            const select = document.getElementById('request_item_id');
            const quantityInput = document.getElementById('quantity');
            const quantityHint = document.getElementById('quantity_hint');
            const quantityStockWarning = document.getElementById('quantity_stock_warning');
            const unitBadge = document.getElementById('unit_badge');
            const stockInfo = document.getElementById('stock_info');
            const previewImage = document.getElementById('item_preview_image');
            const previewName = document.getElementById('item_preview_name');
            const previewUnit = document.getElementById('item_preview_unit');
            const previewStock = document.getElementById('item_preview_stock');
            const previewDescription = document.getElementById('item_preview_description');
            const requestDateInput = document.getElementById('request_date');
            const realizationDateInput = document.getElementById('realization_date');
            const purposeInput = document.getElementById('purpose');
            const submitButton = document.getElementById('submit_request_button');
            const submitButtonLabel = document.getElementById('submit_request_label');
            const stockUnavailableNotice = document.getElementById('stock_unavailable_notice');

            function formatNumber(value) {
                const number = parseFloat(value);
                if (isNaN(number)) return '0';
                return number.toFixed(2).replace(/\.00$/, '').replace(/(\.\d*[1-9])0$/, '$1');
            }

            function setRequestFormDisabled(disabled) {
                [quantityInput, realizationDateInput, purposeInput].forEach((field) => {
                    if (!field) return;

                    field.disabled = disabled;
                    field.classList.toggle('bg-slate-100', disabled);
                    field.classList.toggle('cursor-not-allowed', disabled);
                });

                if (submitButton) {
                    submitButton.disabled = disabled;
                    submitButton.classList.toggle('bg-blue-600', !disabled);
                    submitButton.classList.toggle('hover:bg-blue-700', !disabled);
                    submitButton.classList.toggle('shadow-sm', !disabled);
                    submitButton.classList.toggle('bg-slate-300', disabled);
                    submitButton.classList.toggle('cursor-not-allowed', disabled);
                    submitButton.classList.toggle('opacity-70', disabled);
                    submitButton.classList.toggle('shadow-none', disabled);
                }

                if (submitButtonLabel) {
                    submitButtonLabel.textContent = disabled ? 'Stok Habis' : 'Kirim Permintaan';
                }

                if (stockUnavailableNotice) {
                    stockUnavailableNotice.classList.toggle('hidden', !disabled);
                }
            }

            function getSelectedStock() {
                const selected = select.options[select.selectedIndex];
                if (!selected || !selected.value) return 0;
                return parseFloat(selected.dataset.stock || '0');
            }

            function getSelectedUnit() {
                const selected = select.options[select.selectedIndex];
                if (!selected || !selected.value) return '';
                return selected.dataset.unit || '';
            }

            function applyQuantityRules(unit, stock) {
                if (!quantityInput) return;

                if (unit === 'meter') {
                    quantityInput.step = '0.01';
                    quantityInput.min = '0.01';
                    quantityInput.max = stock > 0 ? stock : '';
                    quantityInput.placeholder = 'Contoh: 2.5';
                    quantityHint.textContent = `Untuk meter, jumlah boleh desimal. Maksimal ${formatNumber(stock)} meter.`;
                } else {
                    quantityInput.step = '1';
                    quantityInput.min = '1';
                    quantityInput.max = stock > 0 ? Math.floor(stock) : '';
                    quantityInput.placeholder = 'Contoh: 2';
                    quantityHint.textContent = `Untuk pcs dan unit, jumlah harus angka bulat. Maksimal ${formatNumber(stock)} ${unit || ''}.`;
                    if (quantityInput.value && quantityInput.value.includes('.')) {
                        quantityInput.value = Math.floor(parseFloat(quantityInput.value)) || '';
                    }
                }
            }

            function validateQuantityAgainstStock() {
                const unit = getSelectedUnit();
                const stock = getSelectedStock();
                const value = parseFloat(quantityInput.value || '0');

                quantityStockWarning.classList.add('hidden');
                quantityStockWarning.textContent = '';

                if (!value || !stock) return;

                if (value > stock) {
                    quantityInput.value = unit === 'meter' ? stock : Math.floor(stock);
                    quantityStockWarning.textContent = `Jumlah melebihi stok. Maksimal permintaan untuk barang ini adalah ${formatNumber(stock)} ${unit}.`;
                    quantityStockWarning.classList.remove('hidden');
                }
            }

            function updatePreview() {
                const selected = select.options[select.selectedIndex];

                if (!selected || !selected.value) {
                    unitBadge.textContent = 'satuan';
                    stockInfo.textContent = 'Pilih barang dulu';
                    previewImage.src = 'https://via.placeholder.com/500x320?text=Preview+Barang';
                    previewName.textContent = 'Belum dipilih';
                    previewUnit.textContent = '-';
                    previewStock.textContent = '-';
                    previewDescription.textContent = 'Pilih barang terlebih dahulu untuk melihat deskripsi.';
                    applyQuantityRules('', 0);
                    return;
                }

                const unit = selected.dataset.unit || '-';
                const image = selected.dataset.image || 'https://via.placeholder.com/500x320?text=Preview+Barang';
                const stock = parseFloat(selected.dataset.stock || '0');
                const description = selected.dataset.description || 'Tidak ada deskripsi barang.';
                const name = selected.textContent.trim();
                const stockFormatted = formatNumber(stock);
                const outOfStock = stock <= 0;

                unitBadge.textContent = unit;
                stockInfo.textContent = `${stockFormatted} ${unit}`;
                previewImage.src = image;
                previewName.textContent = name;
                previewUnit.textContent = unit;
                previewStock.textContent = outOfStock ? `${stockFormatted} ${unit} (stok habis)` : `${stockFormatted} ${unit}`;
                previewDescription.textContent = description;

                applyQuantityRules(unit, stock);
                setRequestFormDisabled(outOfStock);

                if (outOfStock) {
                    quantityInput.value = '';
                    quantityHint.textContent = `Stok ${name} sedang habis. Form permintaan dinonaktifkan sampai stok tersedia kembali.`;
                    quantityStockWarning.classList.add('hidden');
                    quantityStockWarning.textContent = '';
                    return;
                }

                validateQuantityAgainstStock();
            }

            function sanitizeQuantityInput() {
                const unit = getSelectedUnit();

                if (!quantityInput.value) {
                    quantityStockWarning.classList.add('hidden');
                    return;
                }

                if (unit !== 'meter') {
                    quantityInput.value = quantityInput.value.replace('.', '');
                    if (quantityInput.value) {
                        quantityInput.value = Math.floor(parseFloat(quantityInput.value));
                    }
                }

                validateQuantityAgainstStock();
            }

            function syncRealizationMinDate() {
                if (!requestDateInput || !realizationDateInput) return;

                const requestDate = requestDateInput.value;
                realizationDateInput.min = requestDate;

                if (realizationDateInput.value && requestDate && realizationDateInput.value < requestDate) {
                    realizationDateInput.value = requestDate;
                }
            }

            select.addEventListener('change', updatePreview);
            quantityInput.addEventListener('input', sanitizeQuantityInput);
            requestDateInput.addEventListener('change', syncRealizationMinDate);

            updatePreview();
            syncRealizationMinDate();
        });
    </script>
</body>

</html>
