@extends('layouts.app')

@section('content')
    <x-common.page-breadcrumb pageTitle="{{ $title ?? 'Edit Produk' }}" />

    <div x-data="productForm()" x-init="init()" class="mx-auto max-w-2xl">
        <div class="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
            <div class="border-b border-gray-200 px-5 py-4 dark:border-gray-800">
                <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Edit Produk: {{ $product->name }}</h3>
            </div>
            <div class="p-5">
                <form action="{{ route('products.items.update', $product) }}" method="POST" @submit="prepareSubmit">
                    @csrf
                    @method('PUT')
                    <div class="space-y-5">
                        <x-form.input
                            name="name"
                            label="Nama Produk"
                            placeholder="Cetak Banner, Print A3, dll"
                            :value="$product->name"
                            :required="true"
                        />

                        <x-form.input
                            name="code"
                            label="Kode Produk"
                            :value="$product->code"
                        />

                        <x-form.textarea
                            name="description"
                            label="Deskripsi"
                            placeholder="Keterangan produk..."
                            :value="$product->description"
                            rows="3"
                        />

                        <!-- Material Selection with Dialog -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                Bahan yang Tersedia
                                <span class="text-xs text-gray-500 font-normal">(Kosongkan untuk semua bahan)</span>
                            </label>

                            <!-- Selected Materials Display -->
                            <div class="min-h-[60px] p-3 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 mb-2">
                                <template x-if="selectedMaterials.length === 0">
                                    <p class="text-sm text-gray-500 italic">Semua bahan tersedia (tidak ada filter khusus)</p>
                                </template>
                                <div class="flex flex-wrap gap-2">
                                    <template x-for="mat in selectedMaterials" :key="mat.id">
                                        <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-brand-100 text-brand-700 dark:bg-brand-500/20 dark:text-brand-300 text-sm">
                                            <span x-text="mat.name"></span>
                                            <button type="button" @click="removeMaterial(mat.id)" class="hover:text-brand-900 dark:hover:text-white">
                                                <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                                            </button>
                                            <input type="hidden" name="material_ids[]" :value="mat.id">
                                        </span>
                                    </template>
                                </div>
                            </div>

                            <button
                                type="button"
                                @click="showMaterialDialog = true"
                                class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-brand-600 dark:text-brand-400 bg-brand-50 dark:bg-brand-500/10 rounded-lg hover:bg-brand-100 dark:hover:bg-brand-500/20 transition"
                            >
                                <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                                Pilih Bahan
                            </button>
                            <p class="mt-1 text-xs text-gray-500">Klik untuk memilih bahan yang tersedia untuk produk ini.</p>
                        </div>

                        <x-form.select
                            name="is_active"
                            label="Status"
                            placeholder="Pilih Status"
                            :options="['1' => 'Aktif', '0' => 'Nonaktif']"
                            :value="$product->is_active ? '1' : '0'"
                        />

                        <!-- Track Clicks Toggle -->
                        <div class="flex items-center gap-3 pt-2">
                            <label class="relative inline-flex cursor-pointer items-center">
                                <input type="checkbox" name="track_clicks" value="1" {{ $product->track_clicks ? 'checked' : '' }} class="peer sr-only">
                                <div class="peer h-6 w-11 rounded-full bg-gray-200 after:absolute after:left-[2px] after:top-[2px] after:h-5 after:w-5 after:rounded-full after:border after:border-gray-300 after:bg-white after:transition-all after:content-[''] peer-checked:bg-brand-500 peer-checked:after:translate-x-full peer-checked:after:border-white dark:border-gray-600 dark:bg-gray-700"></div>
                            </label>
                            <span class="text-sm font-medium text-gray-700 dark:text-gray-300">Catat Laporan Klik</span>
                        </div>
                    </div>

                    <div class="mt-6 flex items-center gap-3">
                        <button type="submit" class="rounded-lg bg-brand-500 px-6 py-2.5 text-sm font-medium text-white hover:bg-brand-600">
                            Update Produk
                        </button>
                        <a href="{{ route('products.items.index') }}" class="rounded-lg border border-gray-300 px-4 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-600 dark:text-gray-300">
                            Batal
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Material Selection Dialog - rendered via teleport to body -->
        <template x-teleport="body">
            <div
                x-show="showMaterialDialog"
                x-cloak
                class="modal-material-dialog"
                @keydown.escape.window="showMaterialDialog = false"
            >
                <!-- Backdrop -->
                <div
                    class="modal-material-backdrop"
                    @click="showMaterialDialog = false"
                    x-show="showMaterialDialog"
                    x-transition:enter="transition ease-out duration-200"
                    x-transition:enter-start="opacity-0"
                    x-transition:enter-end="opacity-100"
                    x-transition:leave="transition ease-in duration-150"
                    x-transition:leave-start="opacity-100"
                    x-transition:leave-end="opacity-0"
                ></div>

                <!-- Dialog -->
                <div class="modal-material-container">
                    <div
                        class="relative w-full max-w-2xl max-h-[80vh] bg-white dark:bg-gray-900 rounded-2xl shadow-xl flex flex-col"
                        @click.stop
                        x-show="showMaterialDialog"
                        x-transition:enter="transition ease-out duration-200"
                        x-transition:enter-start="opacity-0 scale-95"
                        x-transition:enter-end="opacity-100 scale-100"
                        x-transition:leave="transition ease-in duration-150"
                        x-transition:leave-start="opacity-100 scale-100"
                        x-transition:leave-end="opacity-0 scale-95"
                    >
                        <!-- Header -->
                        <div class="flex items-center justify-between px-5 py-4 border-b border-gray-200 dark:border-gray-700">
                            <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Pilih Bahan</h3>
                            <button type="button" @click="showMaterialDialog = false" class="text-gray-500 hover:text-gray-700 dark:hover:text-gray-300">
                                <svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                            </button>
                        </div>

                        <!-- Search & Filter -->
                        <div class="px-5 py-3 border-b border-gray-200 dark:border-gray-700 space-y-3">
                            <input
                                type="text"
                                x-model="searchQuery"
                                placeholder="Cari bahan..."
                                class="w-full h-10 rounded-lg border border-gray-300 dark:border-gray-600 bg-transparent px-4 text-sm focus:border-brand-500 focus:ring-brand-500 dark:bg-gray-900 dark:text-white"
                            >
                            <div class="flex flex-wrap gap-2">
                                <button
                                    type="button"
                                    @click="filterCategory = ''"
                                    :class="filterCategory === '' ? 'bg-brand-500 text-white' : 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300'"
                                    class="px-3 py-1 text-xs font-medium rounded-full transition"
                                >Semua</button>
                                <template x-for="cat in categories" :key="cat">
                                    <button
                                        type="button"
                                        @click="filterCategory = cat"
                                        :class="filterCategory === cat ? 'bg-brand-500 text-white' : 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300'"
                                        class="px-3 py-1 text-xs font-medium rounded-full transition"
                                        x-text="cat"
                                    ></button>
                                </template>
                            </div>
                        </div>

                        <!-- Material List -->
                        <div class="flex-1 overflow-y-auto p-5">
                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-2">
                                <template x-for="mat in filteredMaterials" :key="mat.id">
                                    <label
                                        class="flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition"
                                        :class="isSelected(mat.id) ? 'border-brand-500 bg-brand-50 dark:bg-brand-500/10' : 'border-gray-200 dark:border-gray-700 hover:border-brand-300'"
                                    >
                                        <input
                                            type="checkbox"
                                            :checked="isSelected(mat.id)"
                                            @change="toggleMaterial(mat)"
                                            class="rounded border-gray-300 text-brand-500 focus:ring-brand-500"
                                        >
                                        <div class="flex-1 min-w-0">
                                            <p class="text-sm font-medium text-gray-800 dark:text-white/90 truncate" x-text="mat.name"></p>
                                            <p class="text-xs text-gray-500">
                                                <span x-text="'Rp ' + formatNumber(mat.base_price) + '/' + mat.unit"></span>
                                                <span x-show="mat.category" class="ml-2 text-brand-600 dark:text-brand-400" x-text="'• ' + mat.category"></span>
                                            </p>
                                        </div>
                                    </label>
                                </template>
                            </div>
                            <template x-if="filteredMaterials.length === 0">
                                <p class="text-center text-gray-500 py-8">Tidak ada bahan ditemukan</p>
                            </template>
                        </div>

                        <!-- Footer -->
                        <div class="flex items-center justify-between px-5 py-4 border-t border-gray-200 dark:border-gray-700">
                            <p class="text-sm text-gray-600 dark:text-gray-400">
                                <span x-text="selectedMaterials.length"></span> bahan dipilih
                            </p>
                            <div class="flex gap-2">
                                <button type="button" @click="selectedMaterials = []" class="px-4 py-2 text-sm font-medium text-gray-600 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200">
                                    Reset
                                </button>
                                <button type="button" @click="showMaterialDialog = false" class="px-4 py-2 text-sm font-medium text-white bg-brand-500 rounded-lg hover:bg-brand-600">
                                    Selesai
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </template>
    </div>
@endsection

@push('scripts')
<script>
function productForm() {
    const allMaterials = @json($materialsJson);
    const selectedIds = @json($selectedMaterialIds);
    const categories = [...new Set(allMaterials.map(m => m.category).filter(c => c))];

    // Pre-select materials
    const initialSelected = allMaterials.filter(m => selectedIds.includes(m.id));

    return {
        allMaterials: allMaterials,
        categories: categories,
        selectedMaterials: initialSelected,
        showMaterialDialog: false,
        searchQuery: '',
        filterCategory: '',

        init() {
            this.$watch('showMaterialDialog', (value) => {
                document.body.style.overflow = value ? 'hidden' : '';
            });
        },

        get filteredMaterials() {
            return this.allMaterials.filter(mat => {
                const matchSearch = !this.searchQuery || mat.name.toLowerCase().includes(this.searchQuery.toLowerCase());
                const matchCategory = !this.filterCategory || mat.category === this.filterCategory;
                return matchSearch && matchCategory;
            });
        },

        isSelected(id) {
            return this.selectedMaterials.some(m => m.id === id);
        },

        toggleMaterial(mat) {
            if (this.isSelected(mat.id)) {
                this.removeMaterial(mat.id);
            } else {
                this.selectedMaterials.push(mat);
            }
        },

        removeMaterial(id) {
            this.selectedMaterials = this.selectedMaterials.filter(m => m.id !== id);
        },

        formatNumber(value) {
            return new Intl.NumberFormat('id-ID').format(value || 0);
        },

        prepareSubmit(e) {
            // Form is ready
        }
    };
}
</script>
@endpush

@push('styles')
<style>
[x-cloak] { display: none !important; }

.modal-material-dialog {
    position: fixed;
    inset: 0;
    z-index: 999999 !important;
    overflow-y: auto;
}

.modal-material-backdrop {
    position: fixed;
    inset: 0;
    background-color: rgba(17, 24, 39, 0.5);
    backdrop-filter: blur(4px);
    z-index: 999999 !important;
}

.modal-material-container {
    position: fixed;
    inset: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 1rem;
    z-index: 1000000 !important;
}
</style>
@endpush
