@extends('layouts.admin')

@section('title', 'Tambah Produk')

@section('content')
<div class="max-w-6xl mx-auto space-y-6">
    
    <!-- Page Header -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
            <h2 class="text-2xl font-bold text-gray-800">Tambah Produk</h2>
            <p class="text-gray-500 mt-1">Isi informasi produk dan varian di bawah ini</p>
        </div>
        <a href="{{ route('produks.index') }}" 
           class="inline-flex items-center gap-2 px-4 py-2 text-gray-600 hover:text-gray-800 font-medium transition-colors">
            <i class="bi bi-arrow-left"></i>
            Kembali ke Daftar
        </a>
    </div>

    <!-- Validation Errors -->
    @if ($errors->any())
        <div x-data="{ show: true }" x-show="show" x-transition class="flex items-start gap-3 px-5 py-4 bg-red-50 border border-red-200 rounded-xl text-red-800">
            <i class="bi bi-exclamation-triangle-fill text-red-500 mt-0.5"></i>
            <div class="flex-1">
                <p class="font-semibold">Terjadi kesalahan validasi:</p>
                <ul class="mt-1 space-y-1 text-sm">
                    @foreach ($errors->all() as $error)
                        <li>• {{ $error }}</li>
                    @endforeach
                </ul>
            </div>
            <button @click="show = false" class="text-red-400 hover:text-red-600 transition-colors">
                <i class="bi bi-x-lg"></i>
            </button>
        </div>
    @endif

    <form action="{{ route('produks.store') }}" method="POST" enctype="multipart/form-data" class="space-y-6">
        @csrf

        {{-- 📦 Informasi Dasar Produk --}}
        <div class="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-100 bg-gradient-to-r from-blue-50 to-indigo-50">
                <h3 class="font-semibold text-gray-800 flex items-center gap-2">
                    <i class="bi bi-info-circle text-blue-500"></i>
                    Informasi Dasar Produk
                </h3>
            </div>
            <div class="p-6 space-y-5">
                
                <!-- Nama Produk -->
                <div>
                    <label for="nama" class="block text-sm font-medium text-gray-700 mb-2">
                        Nama Produk <span class="text-red-500">*</span>
                    </label>
                    <input type="text" name="nama" id="nama" 
                           class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all @error('nama') border-red-400 bg-red-50 @enderror" 
                           value="{{ old('nama') }}" 
                           placeholder="Contoh: Kaos Polos Premium"
                           required>
                    @error('nama')
                        <p class="mt-1.5 text-sm text-red-500 flex items-center gap-1">
                            <i class="bi bi-exclamation-circle"></i> {{ $message }}
                        </p>
                    @enderror
                </div>

                <!-- Deskripsi -->
                <div>
                    <label for="deskripsi" class="block text-sm font-medium text-gray-700 mb-2">
                        Deskripsi
                    </label>
                    <textarea name="deskripsi" id="deskripsi" 
                              class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all resize-y @error('deskripsi') border-red-400 bg-red-50 @enderror" 
                              rows="4" 
                              placeholder="Jelaskan detail produk, bahan, keunggulan, dll.">{{ old('deskripsi') }}</textarea>
                    @error('deskripsi')
                        <p class="mt-1.5 text-sm text-red-500 flex items-center gap-1">
                            <i class="bi bi-exclamation-circle"></i> {{ $message }}
                        </p>
                    @enderror
                </div>

                <!-- Kategori -->
                <div>
                    <label for="kategori_id" class="block text-sm font-medium text-gray-700 mb-2">
                        Kategori <span class="text-red-500">*</span>
                    </label>
                    <select name="kategori_id" id="kategori_id" 
                            class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all bg-white @error('kategori_id') border-red-400 bg-red-50 @enderror" 
                            required>
                        <option value="">-- Pilih Kategori --</option>
                        @foreach($kategoris as $kategori)
                            <option value="{{ $kategori->id }}" {{ old('kategori_id') == $kategori->id ? 'selected' : '' }}>
                                {{ $kategori->nama }}
                            </option>
                        @endforeach
                    </select>
                    @error('kategori_id')
                        <p class="mt-1.5 text-sm text-red-500 flex items-center gap-1">
                            <i class="bi bi-exclamation-circle"></i> {{ $message }}
                        </p>
                    @enderror
                </div>

                <!-- Foto Utama -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        Foto Utama Produk <span class="text-gray-400 font-normal">(Opsional)</span>
                    </label>
                    <div class="mt-2 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-xl hover:border-blue-400 transition-colors bg-gray-50" id="dropzone">
                        <div class="text-center">
                            <i class="bi bi-cloud-upload text-4xl text-gray-400 mb-3"></i>
                            <div class="flex text-sm text-gray-600 justify-center">
                                <label for="foto" class="relative cursor-pointer bg-white rounded-md font-medium text-blue-600 hover:text-blue-500 focus-within:outline-none">
                                    <span>Upload file</span>
                                    <input id="foto" name="foto" type="file" class="sr-only" accept="image/*" @error('foto') border-red-400 @enderror>
                                </label>
                                <p class="pl-1">atau drag & drop</p>
                            </div>
                            <p class="text-xs text-gray-500 mt-2">PNG, JPG, GIF, WEBP hingga 2MB</p>
                            @error('foto')
                                <p class="mt-2 text-sm text-red-500 flex items-center justify-center gap-1">
                                    <i class="bi bi-exclamation-circle"></i> {{ $message }}
                                </p>
                            @enderror
                        </div>
                    </div>
                    <!-- Preview Image -->
                    <div id="foto-preview" class="mt-3 hidden">
                        <img src="" alt="Preview" class="max-h-48 rounded-lg shadow-md border border-gray-200">
                    </div>
                </div>
            </div>
        </div>

        {{-- 🎨 Varian Produk --}}
        <div class="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-100 bg-gradient-to-r from-emerald-50 to-teal-50 flex items-center justify-between">
                <h3 class="font-semibold text-gray-800 flex items-center gap-2">
                    <i class="bi bi-palette text-emerald-500"></i>
                    Varian Produk
                </h3>
                <button type="button" onclick="addVarian()" 
                        class="inline-flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-600 hover:to-teal-700 text-white text-sm font-medium rounded-xl shadow-md shadow-emerald-500/25 hover:shadow-emerald-500/40 transition-all duration-200 transform hover:-translate-y-0.5">
                    <i class="bi bi-plus-lg"></i>
                    Tambah Varian
                </button>
            </div>
            <div class="p-6">
                <div id="varian-container" class="space-y-4">
                    {{-- Varian akan ditambahkan di sini oleh JavaScript --}}
                </div>
                
                <div class="mt-4 p-4 bg-blue-50 rounded-xl border border-blue-100">
                    <p class="text-sm text-blue-700 flex items-start gap-2">
                        <i class="bi bi-info-circle mt-0.5"></i>
                        <span>Minimal satu varian harus diisi. Setiap varian bisa memiliki beberapa foto tambahan untuk menunjukkan detail berbeda.</span>
                    </p>
                </div>
                @error('varians')
                    <p class="mt-3 text-sm text-red-500 flex items-center gap-1">
                        <i class="bi bi-exclamation-circle"></i> {{ $message }}
                    </p>
                @enderror
            </div>
        </div>

        {{-- Action Buttons --}}
        <div class="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 pt-4">
            <button type="submit" 
                    class="flex-1 sm:flex-none inline-flex items-center justify-center gap-2 px-6 py-3 bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white font-semibold rounded-xl shadow-lg shadow-blue-500/25 hover:shadow-blue-500/40 transition-all duration-200 transform hover:-translate-y-0.5">
                <i class="bi bi-check-lg"></i>
                Simpan Produk
            </button>
            <a href="{{ route('produks.index') }}" 
               class="flex-1 sm:flex-none inline-flex items-center justify-center gap-2 px-6 py-3 border border-gray-300 text-gray-700 font-medium rounded-xl hover:bg-gray-50 transition-all duration-200">
                <i class="bi bi-x-lg"></i>
                Batal
            </a>
        </div>
    </form>
</div>

{{-- 🧩 Template untuk satu varian --}}
<template id="varian-template">
    <div class="varian-item relative p-5 bg-gradient-to-br from-gray-50 to-white border border-gray-200 rounded-2xl shadow-sm hover:shadow-md transition-shadow">
        <!-- Decorative left border -->
        <div class="absolute left-0 top-0 bottom-0 w-1 bg-gradient-to-b from-emerald-400 to-teal-500 rounded-l-2xl"></div>
        
        <div class="pl-3">
            <!-- Header Varian -->
            <div class="flex items-center justify-between mb-4 pb-3 border-b border-gray-100">
                <h4 class="font-semibold text-gray-700 flex items-center gap-2">
                    <i class="bi bi-box-seam text-emerald-500"></i>
                    Varian <span class="varian-index text-emerald-600">#INDEX+1</span>
                </h4>
                <button type="button" onclick="removeVarian(this)" 
                        class="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm text-red-600 hover:text-red-700 hover:bg-red-50 rounded-lg transition-colors">
                    <i class="bi bi-trash"></i>
                    Hapus
                </button>
            </div>

            <!-- Form Fields Grid -->
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
                <!-- Ukuran -->
                <div>
                    <label class="block text-xs font-medium text-gray-600 mb-1.5">Ukuran <span class="text-red-500">*</span></label>
                    <input type="text" name="varians[INDEX][ukuran]" class="varian-ukuran w-full px-3.5 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-all text-sm" placeholder="S, M, L, XL" required>
                </div>
                
                <!-- Warna -->
                <div>
                    <label class="block text-xs font-medium text-gray-600 mb-1.5">Warna <span class="text-red-500">*</span></label>
                    <input type="text" name="varians[INDEX][warna]" class="varian-warna w-full px-3.5 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-all text-sm" placeholder="Merah, Biru" required>
                </div>
                
                <!-- Harga -->
                <div>
                    <label class="block text-xs font-medium text-gray-600 mb-1.5">Harga <span class="text-red-500">*</span></label>
                    <input type="number" name="varians[INDEX][harga]" class="varian-harga w-full px-3.5 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-all text-sm" step="0.01" min="0" placeholder="0" required>
                </div>
                
                <!-- Stok -->
                <div>
                    <label class="block text-xs font-medium text-gray-600 mb-1.5">Stok <span class="text-red-500">*</span></label>
                    <input type="number" name="varians[INDEX][stok]" class="varian-stok w-full px-3.5 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-all text-sm" min="0" placeholder="0" required>
                </div>
                
                <!-- SKU -->
                <div>
                    <label class="block text-xs font-medium text-gray-600 mb-1.5">SKU <span class="text-gray-400 font-normal">(Opsional)</span></label>
                    <input type="text" name="varians[INDEX][sku]" class="varian-sku w-full px-3.5 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-all text-sm" placeholder="SKU-001">
                </div>
            </div>

            <!-- Foto Varian -->
            <div class="mt-4 pt-4 border-t border-gray-100">
                <label class="block text-xs font-medium text-gray-600 mb-2">
                    Foto Varian <span class="text-gray-400 font-normal">(Bisa pilih lebih dari satu)</span>
                </label>
                <div class="flex items-center gap-3">
                    <label class="flex-1 flex items-center justify-center px-4 py-3 border-2 border-dashed border-gray-300 rounded-xl hover:border-emerald-400 transition-colors cursor-pointer bg-gray-50 hover:bg-emerald-50/30">
                        <i class="bi bi-images text-gray-400 mr-2"></i>
                        <span class="text-sm text-gray-600">Pilih foto varian</span>
                        <input type="file" name="varians[INDEX][photos][]" class="varian-photos sr-only" multiple accept="image/*">
                    </label>
                </div>
                <p class="text-xs text-gray-500 mt-2 ml-1">PNG, JPG, GIF, WEBP • Maks 2MB per file</p>
                
                <!-- Preview container for variant photos -->
                <div class="varian-photos-preview mt-3 flex flex-wrap gap-2"></div>
            </div>
        </div>
    </div>
</template>

<script>
    let varianIndex = 0;

    // Format currency input (optional enhancement)
    function formatRupiah(element) {
        let value = element.value.replace(/\D/g, '');
        if (value) {
            element.dataset.raw = value;
        }
    }

    // Preview image upload
    function setupImagePreview(input, previewContainer) {
        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = function(e) {
                previewContainer.innerHTML = `<img src="${e.target.result}" class="max-h-32 rounded-lg shadow border border-gray-200">`;
                previewContainer.classList.remove('hidden');
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

    // Tambah varian baru
    function addVarian() {
        const container = document.getElementById('varian-container');
        const template = document.getElementById('varian-template').innerHTML;
        
        // Ganti placeholder INDEX dengan indeks saat ini
        const newVarianHtml = template.replace(/INDEX/g, varianIndex);
        
        // Sisipkan ke dalam container
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = newVarianHtml;
        const newVarian = tempDiv.firstElementChild;
        
        // Update variant number display
        const indexSpan = newVarian.querySelector('.varian-index');
        if (indexSpan) indexSpan.textContent = `#${varianIndex + 1}`;
        
        // Setup image preview for main photo (if this is first variant and we want global preview)
        if (varianIndex === 0) {
            const mainFotoInput = document.getElementById('foto');
            const mainPreview = document.getElementById('foto-preview');
            if (mainFotoInput && mainPreview) {
                mainFotoInput.addEventListener('change', function() {
                    setupImagePreview(this, mainPreview);
                });
            }
        }
        
        // Setup photo preview for variant photos
        const variantPhotoInputs = newVarian.querySelectorAll('.varian-photos');
        variantPhotoInputs.forEach(input => {
            input.addEventListener('change', function() {
                const previewContainer = this.closest('.varian-item').querySelector('.varian-photos-preview');
                previewContainer.innerHTML = '';
                Array.from(this.files).forEach(file => {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const img = document.createElement('img');
                        img.src = e.target.result;
                        img.className = 'max-h-16 rounded-lg shadow border border-gray-200';
                        previewContainer.appendChild(img);
                    }
                    reader.readAsDataURL(file);
                });
            });
        });
        
        container.appendChild(newVarian);
        varianIndex++;
    }

    // Hapus varian
    function removeVarian(button) {
        const varianItem = button.closest('.varian-item');
        varianItem.style.opacity = '0';
        varianItem.style.transform = 'translateX(-20px)';
        varianItem.style.transition = 'all 0.2s ease';
        
        setTimeout(() => {
            varianItem.remove();
            
            // Jika tidak ada varian tersisa, tambahkan satu varian kosong
            const container = document.getElementById('varian-container');
            if (container.children.length === 0) {
                addVarian();
            }
        }, 200);
    }

    // Inisialisasi saat halaman dimuat
    document.addEventListener('DOMContentLoaded', function() {
        // Jika ada old input (gagal validasi), isi ulang varian
        @if(old('varians'))
            const oldVarians = @json(old('varians'));
            oldVarians.forEach((varian, idx) => {
                addVarian();
                const currentVarian = document.querySelectorAll('.varian-item')[idx];
                if (currentVarian) {
                    currentVarian.querySelector('.varian-ukuran').value = varian.ukuran || '';
                    currentVarian.querySelector('.varian-warna').value = varian.warna || '';
                    currentVarian.querySelector('.varian-harga').value = varian.harga || '';
                    currentVarian.querySelector('.varian-stok').value = varian.stok || '';
                    currentVarian.querySelector('.varian-sku').value = varian.sku || '';
                }
            });
        @else
            // Tambahkan satu varian kosong saat pertama kali
            addVarian();
        @endif

        // Setup main foto preview
        const mainFotoInput = document.getElementById('foto');
        const mainPreview = document.getElementById('foto-preview');
        if (mainFotoInput && mainPreview) {
            mainFotoInput.addEventListener('change', function() {
                setupImagePreview(this, mainPreview);
            });
        }
    });
</script>

<style>
    /* Smooth transitions for dynamic elements */
    .varian-item {
        animation: slideIn 0.3s ease-out;
    }
    @keyframes slideIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    /* Custom file input styling enhancement */
    input[type="file"]::-webkit-file-upload-button {
        visibility: hidden;
        width: 0;
    }
</style>
@endsection