@extends('layouts.app')

@section('content')
    @php
        $initialComponents = collect(old('components', []))
            ->filter(function ($item) {
                return !empty($item['component_material_id']) || (($item['qty'] ?? '') !== '');
            })
            ->map(function ($item) {
                return [
                    'component_material_id' => (string) ($item['component_material_id'] ?? ''),
                    'qty' => (float) ($item['qty'] ?? 1),
                ];
            })
            ->values()
            ->all();

        $initialPriceGroups = collect(old('prices', []))
            ->chunk(2)
            ->map(function ($chunk) {
                $umum = collect($chunk)->firstWhere('member_type', 'umum');
                $studio = collect($chunk)->firstWhere('member_type', 'studio');

                return [
                    'sisi' => (int) ($umum['sisi'] ?? $studio['sisi'] ?? 1),
                    'min_qty' => (int) ($umum['min_qty'] ?? $studio['min_qty'] ?? 1),
                    'max_qty' => $umum['max_qty'] ?? $studio['max_qty'] ?? null,
                    'price_umum' => (float) ($umum['price'] ?? 0),
                    'price_instansi' => (float) ($studio['price'] ?? 0),
                ];
            })
            ->values()
            ->all();
    @endphp

    <div class="rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03] lg:p-6">
        <div class="mb-6">
            <h2 class="text-xl font-semibold text-gray-800 dark:text-white/90">{{ $title }}</h2>
        </div>

        <form action="{{ route('stock.materials.store') }}" method="POST" class="space-y-5" x-data="materialForm()">
            @csrf

            <div class="grid grid-cols-1 gap-5 md:grid-cols-2">
                <div>
                    <label for="name" class="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-300">
                        Nama Bahan <span class="text-error-500">*</span>
                    </label>
                    <input type="text" name="name" id="name" value="{{ old('name') }}"
                        class="h-11 block w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-500 focus:ring-brand-500 dark:border-gray-600 dark:text-white/90"
                        required>
                    @error('name')
                        <p class="mt-1 text-xs text-error-500">{{ $message }}</p>
                    @enderror
                </div>

                <x-form.select
                    name="category_id"
                    label="Kategori"
                    placeholder="Pilih Kategori"
                    :value="old('category_id')"
                    :options="$categories->pluck('name', 'id')->toArray()"
                    :searchable="true"
                />

                <div>
                    <label for="base_price" class="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-300">
                        Harga Dasar <span class="text-error-500">*</span>
                    </label>
                    <input type="number" name="base_price" id="base_price" value="{{ old('base_price', 0) }}"
                        min="0" step="any"
                        class="h-11 block w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-500 focus:ring-brand-500 dark:border-gray-600 dark:text-white/90"
                        required>
                    <p class="mt-1 text-xs text-gray-500">
                        Manual: harga per unit • m²: harga per meter persegi • Roll: harga per meter panjang
                    </p>
                    @error('base_price')
                        <p class="mt-1 text-xs text-error-500">{{ $message }}</p>
                    @enderror
                </div>

                <div>
                    <label for="unit" class="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-300">
                        Satuan <span class="text-error-500">*</span>
                    </label>
                    <input type="text" name="unit" id="unit" value="{{ old('unit', 'pcs') }}"
                        placeholder="pcs, meter, m2, kg, dll"
                        class="h-11 block w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-500 focus:ring-brand-500 dark:border-gray-600 dark:text-white/90"
                        required>
                    @error('unit')
                        <p class="mt-1 text-xs text-error-500">{{ $message }}</p>
                    @enderror
                </div>

                <div class="md:col-span-2 rounded-xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-800/50">
                    <h3 class="text-sm font-semibold text-gray-800 dark:text-white/90">Mode Perhitungan</h3>
                    <p class="mt-1 text-xs text-gray-500">
                        Manual = stok biasa • m² = stok & harga dihitung per meter persegi • Roll = stok & harga dihitung per meter panjang roll
                    </p>

                    <div class="mt-4 grid grid-cols-1 gap-5 md:grid-cols-3">
                        <div>
                            <label for="measurement_mode" class="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Mode Hitung
                            </label>
                            <select name="measurement_mode" id="measurement_mode" x-model="measurementMode"
                                class="h-11 block w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-500 focus:ring-brand-500 dark:border-gray-600 dark:bg-transparent dark:text-white/90">
                                <option value="manual">Manual</option>
                                <option value="m2">m²</option>
                                <option value="roll">Roll</option>
                            </select>
                            @error('measurement_mode')
                                <p class="mt-1 text-xs text-error-500">{{ $message }}</p>
                            @enderror
                        </div>

                        <div x-show="measurementMode === 'roll'" x-cloak>
                            <label for="roll_width_cm" class="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Lebar Roll (cm) <span class="text-error-500">*</span>
                            </label>
                            <input type="number" name="roll_width_cm" id="roll_width_cm"
                                value="{{ old('roll_width_cm') }}" min="0.0001" step="any"
                                class="h-11 block w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-500 focus:ring-brand-500 dark:border-gray-600 dark:text-white/90">
                            @error('roll_width_cm')
                                <p class="mt-1 text-xs text-error-500">{{ $message }}</p>
                            @enderror
                        </div>

                        <div x-show="measurementMode === 'roll'" x-cloak>
                            <label class="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Opsi Roll
                            </label>
                            <input type="hidden" name="allow_rotation" value="0">
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="allow_rotation" value="1" class="sr-only peer"
                                    {{ old('allow_rotation', 1) ? 'checked' : '' }}>
                                <div class="h-6 w-11 rounded-full bg-gray-200 peer dark:bg-gray-700 peer-checked:bg-brand-600 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-brand-300 dark:peer-focus:ring-brand-800 after:absolute after:start-[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:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white dark:border-gray-600"></div>
                                <span class="ms-3 text-sm font-medium text-gray-700 dark:text-gray-300">
                                    Boleh rotasi ukuran
                                </span>
                            </label>
                        </div>
                    </div>

                    <div class="mt-3 text-xs text-gray-500" x-show="measurementMode === 'm2'" x-cloak>
                        Contoh: 100 x 50 cm = 0.5 m². Jika harga dasar 70.000, hasil harga = 35.000.
                    </div>
                    <div class="mt-3 text-xs text-gray-500" x-show="measurementMode === 'roll'" x-cloak>
                        Contoh: lebar roll 100 cm, ukuran 100 x 50 cm = pemakaian 50 cm = 0.5 meter. Jika harga dasar 70.000, hasil harga = 35.000.
                    </div>
                </div>

                <div class="md:col-span-2 rounded-xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-800/50">
                    <div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                        <div>
                            <h3 class="text-sm font-semibold text-gray-800 dark:text-white/90">Bahan Custom</h3>
                            <p class="mt-1 text-xs text-gray-500">
                                Aktifkan jika bahan ini mengambil stok dari satu atau lebih bahan lain
                            </p>
                        </div>

                        <label class="relative inline-flex items-center cursor-pointer">
                            <input type="checkbox" x-model="isCustom" class="sr-only peer">
                            <div class="h-6 w-11 rounded-full bg-gray-200 peer dark:bg-gray-700 peer-checked:bg-brand-600 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-brand-300 dark:peer-focus:ring-brand-800 after:absolute after:start-[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:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white dark:border-gray-600"></div>
                            <span class="ms-3 text-sm font-medium text-gray-700 dark:text-gray-300">Aktifkan</span>
                        </label>
                    </div>

                    <input type="hidden" name="is_custom" :value="isCustom ? 1 : 0">

                    <div x-show="!isCustom" x-cloak class="mt-4 grid grid-cols-1 gap-5 md:grid-cols-2">
                        <div>
                            <label for="stock" class="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Stok Awal
                            </label>
                            <input type="number" name="stock" id="stock" value="{{ old('stock', 0) }}"
                                min="0" step="any" :disabled="isCustom"
                                class="h-11 block w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-500 focus:ring-brand-500 dark:border-gray-600 dark:text-white/90">
                            @error('stock')
                                <p class="mt-1 text-xs text-error-500">{{ $message }}</p>
                            @enderror
                        </div>

                        <div>
                            <label for="min_stock" class="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Minimal Stok
                            </label>
                            <input type="number" name="min_stock" id="min_stock" value="{{ old('min_stock', 0) }}"
                                min="0" step="any" :disabled="isCustom"
                                class="h-11 block w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-500 focus:ring-brand-500 dark:border-gray-600 dark:text-white/90">
                            <p class="mt-1 text-xs text-gray-500">Akan memberi peringatan jika stok di bawah nilai ini</p>
                            @error('min_stock')
                                <p class="mt-1 text-xs text-error-500">{{ $message }}</p>
                            @enderror
                        </div>
                    </div>

                    <div x-show="isCustom" x-cloak class="mt-4 rounded-lg border border-brand-200 bg-brand-50 px-4 py-3 text-sm text-brand-700 dark:border-brand-500/30 dark:bg-brand-500/10 dark:text-brand-300">
                        Stok bahan custom tidak dihitung dari kolom stok bahan ini. Sistem akan mengecek dan mengurangi stok dari bahan komponennya.
                    </div>

                    <div x-show="isCustom" x-cloak class="mt-4 space-y-4">
                        <div class="flex items-center justify-between">
                            <div>
                                <h4 class="text-sm font-medium text-gray-800 dark:text-white/90">Komponen Bahan</h4>
                                <p class="text-xs text-gray-500">Bisa 1, 2, 3, atau lebih bahan</p>
                            </div>

                            <button type="button" @click="addComponent()"
                                class="inline-flex items-center gap-1.5 rounded-lg bg-brand-50 px-3 py-2 text-sm font-medium text-brand-600 transition-colors hover:bg-brand-100 dark:bg-brand-500/10 dark:text-brand-400 dark:hover:bg-brand-500/20">
                                + Tambah Komponen
                            </button>
                        </div>

                        @error('components')
                            <p class="text-xs text-error-500">{{ $message }}</p>
                        @enderror

                        <div class="overflow-x-auto rounded-lg border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-800">
                            <table class="w-full text-sm">
                                <thead class="bg-gray-50 dark:bg-gray-800">
                                    <tr>
                                        <th class="px-3 py-2 text-left font-medium text-gray-500 dark:text-gray-400">Bahan</th>
                                        <th class="px-3 py-2 text-left font-medium text-gray-500 dark:text-gray-400">Qty Pakai</th>
                                        <th class="w-10"></th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-gray-100 dark:divide-gray-800">
                                    <template x-for="(component, idx) in components" :key="idx">
                                        <tr>
                                            <td class="p-2">
                                                <select x-model="component.component_material_id"
                                                    class="h-10 w-full rounded border border-gray-300 px-2 text-sm dark:border-gray-600 dark:bg-gray-800">
                                                    <option value="">Pilih bahan</option>
                                                    @foreach($materials as $sourceMaterial)
                                                        <option value="{{ $sourceMaterial->id }}">
                                                            {{ $sourceMaterial->name }} ({{ $sourceMaterial->unit }})
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </td>
                                            <td class="p-2">
                                                <input type="number" x-model="component.qty" min="0.0001" step="any"
                                                    class="h-10 w-full rounded border border-gray-300 px-2 text-sm dark:border-gray-600 dark:bg-gray-800"
                                                    placeholder="contoh: 0.5">
                                            </td>
                                            <td class="p-2 text-center">
                                                <button type="button" @click="removeComponent(idx)" class="text-gray-400 hover:text-red-500">
                                                    ✕
                                                </button>
                                            </td>
                                        </tr>
                                    </template>
                                </tbody>
                            </table>

                            <div x-show="components.length === 0" class="p-4 text-center text-sm text-gray-500">
                                Belum ada komponen bahan
                            </div>
                        </div>

                        <template x-for="(component, idx) in components" :key="'hidden-component-' + idx">
                            <div>
                                <input type="hidden" :name="`components[${idx}][component_material_id]`" :value="component.component_material_id">
                                <input type="hidden" :name="`components[${idx}][qty]`" :value="component.qty">
                            </div>
                        </template>
                    </div>
                </div>
            </div>

            <div>
                <label class="relative inline-flex items-center cursor-pointer">
                    <input type="checkbox" name="track_clicks" value="1" class="sr-only peer" {{ old('track_clicks') ? 'checked' : '' }}>
                    <div class="h-6 w-11 rounded-full bg-gray-200 peer dark:bg-gray-700 peer-checked:bg-brand-600 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-brand-300 dark:peer-focus:ring-brand-800 after:absolute after:start-[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:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white dark:border-gray-600"></div>
                    <span class="ms-3 text-sm font-medium text-gray-700 dark:text-gray-300">Track Klik</span>
                </label>
            </div>

            <div class="border-t border-gray-200 pt-5 dark:border-gray-700">
                <div class="mb-4 flex items-center justify-between">
                    <div>
                        <h3 class="text-base font-semibold text-gray-800 dark:text-white/90">Aturan Harga</h3>
                        <p class="mt-0.5 text-xs text-gray-500">Atur harga berbeda berdasarkan jumlah qty dan sisi cetak</p>
                    </div>
                    <button type="button" @click="addPriceGroup()"
                        class="inline-flex items-center gap-1.5 rounded-lg bg-brand-50 px-3 py-2 text-sm font-medium text-brand-600 transition-colors hover:bg-brand-100 dark:bg-brand-500/10 dark:text-brand-400 dark:hover:bg-brand-500/20">
                        + Tambah Aturan
                    </button>
                </div>

                <div class="rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-800/50">
                    <div class="mb-4 flex items-center justify-between">
                        <h3 class="text-sm font-medium text-gray-800 dark:text-white/90">Aturan Harga Bertingkat</h3>
                        <button type="button" @click="addPriceGroup()" class="text-xs font-medium text-brand-500 hover:text-brand-600">
                            + Tambah Baris
                        </button>
                    </div>

                    <div class="overflow-x-auto rounded-lg border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-800">
                        <table class="w-full text-sm">
                            <thead class="bg-gray-50 dark:bg-gray-800">
                                <tr>
                                    <th class="px-3 py-2 text-left font-medium text-gray-500 dark:text-gray-400">Sisi</th>
                                    <th class="px-3 py-2 text-left font-medium text-gray-500 dark:text-gray-400">Qty Min</th>
                                    <th class="px-3 py-2 text-left font-medium text-gray-500 dark:text-gray-400">Qty Max</th>
                                    <th class="px-3 py-2 text-right font-medium text-gray-500 dark:text-gray-400">Harga Umum</th>
                                    <th class="px-3 py-2 text-right font-medium text-gray-500 dark:text-gray-400">Harga Instansi</th>
                                    <th class="w-8"></th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100 dark:divide-gray-800">
                                <template x-for="(group, idx) in priceGroups" :key="idx">
                                    <tr class="group hover:bg-gray-50 dark:hover:bg-gray-800/50">
                                        <td class="p-2">
                                            <select x-model.number="group.sisi" class="h-9 w-full rounded border border-gray-300 px-2 text-sm dark:border-gray-600 dark:bg-gray-800">
                                                <option value="1">1 Sisi</option>
                                                <option value="2">2 Sisi</option>
                                            </select>
                                        </td>
                                        <td class="p-2">
                                            <input type="number" x-model.number="group.min_qty" min="1" class="h-9 w-full rounded border border-gray-300 px-2 text-sm dark:border-gray-600 dark:bg-gray-800">
                                        </td>
                                        <td class="p-2">
                                            <input type="number" x-model.number="group.max_qty" placeholder="∞" class="h-9 w-full rounded border border-gray-300 px-2 text-sm dark:border-gray-600 dark:bg-gray-800">
                                        </td>
                                        <td class="p-2">
                                            <input type="number" x-model.number="group.price_umum" min="0" step="any" class="h-9 w-full rounded border border-gray-300 px-2 text-right text-sm dark:border-gray-600 dark:bg-gray-800">
                                        </td>
                                        <td class="p-2">
                                            <input type="number" x-model.number="group.price_instansi" min="0" step="any" class="h-9 w-full rounded border border-gray-300 px-2 text-right text-sm dark:border-gray-600 dark:bg-gray-800">
                                        </td>
                                        <td class="p-2 text-center">
                                            <button type="button" @click="removePriceGroup(idx)" class="text-gray-400 hover:text-red-500">
                                                ✕
                                            </button>
                                        </td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>

                        <div x-show="priceGroups.length === 0" class="border-t border-gray-100 p-8 text-center text-sm text-gray-500 dark:border-gray-800">
                            Belum ada aturan harga. Klik tombol tambah di atas.
                        </div>
                    </div>
                </div>

                <template x-for="(group, idx) in priceGroups" :key="'hidden-price-' + idx">
                    <div>
                        <input type="hidden" :name="`prices[${idx * 2}][member_type]`" value="umum">
                        <input type="hidden" :name="`prices[${idx * 2}][sisi]`" :value="group.sisi">
                        <input type="hidden" :name="`prices[${idx * 2}][min_qty]`" :value="group.min_qty">
                        <input type="hidden" :name="`prices[${idx * 2}][max_qty]`" :value="group.max_qty">
                        <input type="hidden" :name="`prices[${idx * 2}][price]`" :value="group.price_umum">

                        <input type="hidden" :name="`prices[${idx * 2 + 1}][member_type]`" value="studio">
                        <input type="hidden" :name="`prices[${idx * 2 + 1}][sisi]`" :value="group.sisi">
                        <input type="hidden" :name="`prices[${idx * 2 + 1}][min_qty]`" :value="group.min_qty">
                        <input type="hidden" :name="`prices[${idx * 2 + 1}][max_qty]`" :value="group.max_qty">
                        <input type="hidden" :name="`prices[${idx * 2 + 1}][price]`" :value="group.price_instansi">
                    </div>
                </template>
            </div>

            <div class="flex items-center justify-end gap-3 pt-4">
                <a href="{{ route('stock.materials.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 dark:hover:bg-gray-800">
                    Batal
                </a>
                <button type="submit"
                    class="rounded-lg bg-brand-500 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-600">
                    Simpan
                </button>
            </div>
        </form>
    </div>
@endsection

@push('scripts')
<script>
function materialForm() {
    return {
        isCustom: @json((bool) old('is_custom', false)),
        measurementMode: @json(old('measurement_mode', 'manual')),
        components: @json($initialComponents),
        priceGroups: @json($initialPriceGroups),

        init() {
            if (!this.priceGroups || this.priceGroups.length === 0) {
                this.addPriceGroup();
            }

            if (this.isCustom && this.components.length === 0) {
                this.addComponent();
            }

            this.$watch('isCustom', (value) => {
                if (value && this.components.length === 0) {
                    this.addComponent();
                }
            });
        },

        addComponent() {
            this.components.push({
                component_material_id: '',
                qty: 1
            });
        },

        removeComponent(idx) {
            this.components.splice(idx, 1);
        },

        addPriceGroup() {
            this.priceGroups.push({
                sisi: 1,
                min_qty: 1,
                max_qty: null,
                price_umum: 0,
                price_instansi: 0
            });
        },

        removePriceGroup(idx) {
            this.priceGroups.splice(idx, 1);
        }
    };
}
</script>
@endpush