<template>
    <div class="min-h-screen bg-gradient-to-br from-gray-50 to-blue-50/30 pb-32">

        <!-- STICKY HEADER -->
        <div class="sticky top-0 z-50 bg-gradient-to-r from-blue-700 to-blue-800 shadow-lg">
            <div class="px-3 pt-3 pb-2">
                <Link href="/sales/taking-order/dashboard"
                    class="inline-flex items-center gap-2 text-white hover:text-blue-200 transition">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                    </svg>
                    <span class="text-sm">Kembali</span>
                </Link>
            </div>

            <div class="px-3 pb-3">
                <div class="bg-white/15 backdrop-blur-md rounded-xl p-3 border border-white/20">
                    <div class="flex justify-between items-start">
                        <div class="flex-1">
                            <p class="text-blue-100 text-xs mb-1 flex items-center gap-1">
                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                </svg>
                                Customer
                            </p>
                            <h2 class="text-white font-bold text-base">{{ customer.name }}</h2>
                            <p class="text-blue-100 text-xs mt-1 line-clamp-2">{{ customer.address }}</p>
                            <p class="text-blue-100 text-xs mt-1">📞 {{ customer.phone }}</p>
                        </div>
                        <div
                            class="bg-gradient-to-r from-orange-500 to-orange-600 px-3 py-2 rounded-xl text-center ml-3 shadow-lg min-w-[90px]">
                            <p class="text-orange-100 text-xs">Plafon</p>
                            <p class="font-bold text-white text-sm">Rp {{ formatRupiah(customer.plafon) }}</p>
                        </div>
                    </div>
                </div>
            </div>

        </div>

        <!-- Daftar Produk per Kategori -->
        <main class="px-3 py-3">
            <div class="flex justify-between items-center mb-3">
                <h2 class="text-sm font-semibold text-gray-800 flex items-center gap-2">
                    <svg class="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M20 7v10a2 2 0 01-2 2H6a2 2 0 01-2-2V7m16 0a2 2 0 00-2-2H6a2 2 0 00-2 2m16 0l-3.586-3.586A2 2 0 0016.172 3H7.828a2 2 0 00-1.414.586L4 7" />
                    </svg>
                    Pilih Produk
                </h2>
                <span class="text-xs text-gray-500">{{ categories.length }} Kategori</span>
            </div>

            <!-- Info Order Existing -->
            <div v-if="existingOrderId" class="bg-green-50 border-l-4 border-green-500 p-2 mb-3 rounded">
                <p class="text-xs text-green-700">
                    ✅ Anda sudah memiliki order pending untuk customer ini.
                    <span class="font-semibold">Klik + untuk menambah quantity</span>
                </p>
            </div>

            <!-- Offline Mode Indicator -->
            <div v-if="!isOnline" class="bg-yellow-50 border-l-4 border-yellow-500 p-2 mb-3 rounded">
                <p class="text-xs text-yellow-700">
                    📱 Anda sedang offline. Order akan disimpan secara lokal dan di-sync otomatis saat online.
                </p>
            </div>

            <!-- List Categories & Products -->
            <div v-if="categories.length > 0" class="space-y-2">
                <div v-for="category in categories" :key="category.id"
                    class="bg-white rounded-xl shadow-md overflow-hidden">
                    <!-- Category Header -->
                    <button @click="toggleCategory(category.id)"
                        class="w-full flex justify-between items-center p-3 bg-gradient-to-r from-gray-50 to-gray-100 hover:from-blue-50 hover:to-gray-50 transition">
                        <div class="flex items-center gap-2">
                            <div class="w-7 h-7 bg-blue-100 rounded-lg flex items-center justify-center">
                                <span class="text-blue-600 text-xs font-bold">{{ category.products.length }}</span>
                            </div>
                            <span class="font-semibold text-gray-800 text-sm">{{ category.name }}</span>
                        </div>
                        <span class="text-blue-600 text-xl font-bold">
                            {{ isCategoryOpen(category.id) ? '−' : '+' }}
                        </span>
                    </button>

                    <!-- Products List -->
                    <div v-show="isCategoryOpen(category.id)" class="divide-y divide-gray-100">
                        <div v-for="product in category.products" :key="product.id"
                            class="p-3 hover:bg-gray-50 transition"
                            :class="product.existing_qty > 0 ? 'bg-green-50' : ''">
                            <div class="flex gap-2">

                                <!-- Product Image -->
                                <!-- <img
                                    :src="product.image || 'https://via.placeholder.com/80x80?text=No+Image'"
                                    :alt="product.name"
                                    class="w-16 h-16 object-cover rounded-lg cursor-pointer"
                                    @click="showDetail(product)"
                                > -->

                                <div class="flex-1">
                                    <div class="flex justify-between items-start gap-2">
                                        <div class="flex-1">
                                            <div class="flex items-center gap-2">
                                                <h4 class="font-semibold text-gray-800 text-sm cursor-pointer hover:text-blue-600"
                                                    @click="showDetail(product)">
                                                    {{ product.name }}
                                                </h4>
                                                <!-- Badge Existing Order -->
                                                <span v-if="product.existing_qty > 0"
                                                    class="bg-green-500 text-white text-[10px] px-1.5 py-0.5 rounded-full">
                                                    +{{ product.existing_qty }}
                                                </span>
                                            </div>
                                            <p class="text-xs text-gray-500 mt-0.5">SKU: {{ product.sku }}</p>

                                            <!-- Pilihan Satuan -->
                                            <div class="flex items-center gap-2 mt-1 flex-wrap">
                                                <!-- Tombol Satuan Besar -->
                                                <button @click="selectUnit(product.id, 'bulk')"
                                                    class="text-xs px-2 py-0.5 rounded-full transition" :class="getSelectedUnit(product.id) === 'bulk'
                                                        ? 'bg-blue-600 text-white'
                                                        : 'bg-gray-200 text-gray-600 hover:bg-gray-300'">
                                                    {{ product.bulk_unit }} ({{ product.bulk_quantity }} {{
                                                    product.retail_unit }})
                                                </button>

                                                <!-- Tombol Satuan Eceran -->
                                                <button @click="selectUnit(product.id, 'retail')"
                                                    class="text-xs px-2 py-0.5 rounded-full transition" :class="getSelectedUnit(product.id) === 'retail'
                                                        ? 'bg-blue-600 text-white'
                                                        : 'bg-gray-200 text-gray-600 hover:bg-gray-300'">
                                                    {{ product.retail_unit }}
                                                </button>

                                                <!-- Harga -->
                                                <span class="text-orange-600 font-bold text-sm ml-1">
                                                    Rp {{ formatRupiah(getProductPrice(product)) }}
                                                </span>
                                                <span class="text-[10px] text-gray-400">
                                                    / {{ getSelectedUnit(product.id) === 'bulk' ? product.bulk_unit :
                                                    product.retail_unit }}
                                                </span>
                                            </div>
                                            <div class="text-[10px] text-gray-400 mt-0.5">
                                                Stock: {{ product.stock }} {{ product.bulk_unit }}
                                            </div>
                                        </div>

                                        <!-- Quantity Selector -->
                                        <div class="flex items-center gap-1">
                                            <button @click="updateQty(product.id, -1, getProductPrice(product))"
                                                :disabled="getTotalQty(product.id) === 0"
                                                class="w-7 h-7 rounded-full bg-gray-200 text-gray-700 font-bold disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-300 transition text-sm">
                                                -
                                            </button>
                                            <div class="text-center">
                                                <span class="w-7 text-center font-semibold text-sm block">
                                                    {{ getTotalQty(product.id) }}
                                                </span>
                                                <span class="text-[8px] text-gray-400 block">
                                                    {{ getSelectedUnit(product.id) === 'bulk' ? product.bulk_unit :
                                                    product.retail_unit }}
                                                </span>
                                            </div>
                                            <button @click="updateQty(product.id, 1, getProductPrice(product))"
                                                :disabled="getTotalQty(product.id) >= product.stock"
                                                class="w-7 h-7 rounded-full bg-gradient-to-r from-blue-600 to-blue-700 text-white font-bold hover:from-blue-700 hover:to-blue-800 transition disabled:opacity-50 text-sm">
                                                +
                                            </button>
                                        </div>
                                    </div>

                                    <!-- Info Existing Order -->
                                    <div v-if="product.existing_qty > 0" class="mt-1 text-xs text-green-600">
                                        ✓ Sudah diorder: {{ product.existing_qty }} {{ product.bulk_unit }}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Empty State -->
            <div v-else class="text-center py-10">
                <div class="w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-3">
                    <svg class="w-10 h-10 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M20 7v10a2 2 0 01-2 2H6a2 2 0 01-2-2V7m16 0a2 2 0 00-2-2H6a2 2 0 00-2 2m16 0l-3.586-3.586A2 2 0 0016.172 3H7.828a2 2 0 00-1.414.586L4 7" />
                    </svg>
                </div>
                <h3 class="text-base font-semibold text-gray-600">Belum ada produk</h3>
                <p class="text-xs text-gray-400 mt-1">Silakan hubungi admin untuk menambahkan produk</p>
            </div>

            <div class="h-20"></div>
        </main>

        <!-- Bottom Cart Summary -->
        <div class="fixed bottom-0 left-0 right-0 bg-white border-t-2 border-orange-200 shadow-lg transition-transform duration-300 z-50"
            :class="totalItems > 0 ? 'translate-y-0' : 'translate-y-full'">
            <div class="p-3">
                <div class="flex justify-between items-center mb-2">
                    <div>
                        <p class="text-xs text-gray-500">Total Item</p>
                        <p class="font-bold text-lg text-blue-800">{{ totalItems }}</p>
                    </div>
                    <div class="text-right">
                        <p class="text-xs text-gray-500">Total Belanja</p>
                        <p class="font-bold text-base text-orange-600">Rp {{ formatRupiah(totalAmount) }}</p>
                    </div>
                </div>

                <button @click="submitOrder"
                    class="w-full bg-gradient-to-r from-orange-500 to-orange-600 text-white py-2.5 rounded-xl font-semibold text-sm hover:from-orange-600 hover:to-orange-700 transition-all duration-200 active:scale-95 shadow-lg">
                    {{ existingOrderId ? 'Update Order' : 'Proses PO' }} ({{ totalItems }} item)
                </button>
            </div>
        </div>

        <!-- Modal Detail Produk -->
        <div v-if="selectedProduct" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70"
            @click="closeDetail">
            <div class="bg-white rounded-2xl max-w-md w-full overflow-hidden shadow-2xl animate-fade-in-up"
                @click.stop">
                <div class="relative">
                    <img :src="selectedProduct.image || 'https://via.placeholder.com/400x300?text=No+Image'"
                        :alt="selectedProduct.name" class="w-full h-56 object-cover">
                    <button @click="closeDetail"
                        class="absolute top-2 right-2 w-7 h-7 bg-black/50 rounded-full flex items-center justify-center text-white hover:bg-black/70 transition text-sm">
                        ✕
                    </button>
                </div>

                <div class="p-4">
                    <h3 class="text-lg font-bold text-gray-800">{{ selectedProduct.name }}</h3>
                    <p class="text-xs text-gray-500 mt-1">SKU: {{ selectedProduct.sku }}</p>

                    <!-- Harga & Satuan -->
                    <div class="mt-3 space-y-2">
                        <div class="flex items-center justify-between bg-blue-50 p-2 rounded-lg">
                            <span class="text-sm font-semibold">{{ selectedProduct.bulk_unit }}</span>
                            <span class="text-sm font-bold text-orange-600">Rp {{ formatRupiah(selectedProduct.price)
                                }}</span>
                            <span class="text-xs text-gray-500">({{ selectedProduct.bulk_quantity }} {{
                                selectedProduct.retail_unit }})</span>
                        </div>
                        <div class="flex items-center justify-between bg-gray-50 p-2 rounded-lg">
                            <span class="text-sm font-semibold">Per {{ selectedProduct.retail_unit }}</span>
                            <span class="text-sm font-bold text-orange-600">Rp {{ formatRupiah(selectedProduct.price /
                                selectedProduct.bulk_quantity) }}</span>
                        </div>
                    </div>

                    <div class="mt-3 text-xs text-gray-500">
                        Stock: {{ selectedProduct.stock }} {{ selectedProduct.bulk_unit }}
                        <span v-if="selectedProduct.existing_qty > 0" class="text-green-600 font-semibold ml-2">
                            Sudah order: {{ selectedProduct.existing_qty }} {{ selectedProduct.bulk_unit }}
                        </span>
                    </div>

                    <div class="mt-4 pt-3 border-t border-gray-100">
                        <p class="text-xs font-semibold text-gray-700 mb-2">Deskripsi Produk:</p>
                        <p class="text-xs text-gray-600 leading-relaxed">
                            {{ selectedProduct.description || 'Tidak ada deskripsi untuk produk ini.' }}
                        </p>
                    </div>

                    <div class="flex gap-3 mt-5">
                        <button @click="addToCartFromDetail"
                            class="flex-1 bg-gradient-to-r from-blue-600 to-blue-700 text-white py-2.5 rounded-xl font-semibold text-sm hover:from-blue-700 hover:to-blue-800 transition">
                            + Tambah ke Order
                        </button>
                        <button @click="closeDetail"
                            class="flex-1 bg-gray-200 text-gray-700 py-2.5 rounded-xl font-semibold text-sm hover:bg-gray-300 transition">
                            Tutup
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Link, router } from '@inertiajs/vue3'
import { useOfflineManager } from '@/Modules/TakingOrder/Composables/useOfflineManager'

const props = defineProps({
    customer: {
        type: Object,
        required: true
    },
    categories: {
        type: Array,
        default: () => []
    },
    existing_order_id: {
        type: Number,
        default: null
    }
})

// Offline Manager
const { isOnline, saveOrderOffline, pendingOrders } = useOfflineManager()

// Cart state - untuk tambahan order baru
const cart = ref({})

// Open category state - semua tertutup
const openCategoryId = ref(null)

// Selected product for modal
const selectedProduct = ref(null)

// State untuk unit yang dipilih per produk
const selectedUnit = ref({})

// FUNGSI FORMAT RUPIAH
const formatRupiah = (value) => {
    if (!value && value !== 0) return '0'
    return new Intl.NumberFormat('id-ID').format(value)
}

// Fungsi select unit
const selectUnit = (productId, unitType) => {
    selectedUnit.value[productId] = unitType
}

// Fungsi get selected unit
const getSelectedUnit = (productId) => {
    return selectedUnit.value[productId] || 'bulk' // default bulk
}

// Fungsi get price berdasarkan unit yang dipilih
const getProductPrice = (product) => {
    const unit = getSelectedUnit(product.id)
    if (unit === 'retail') {
        return product.retail_price || (product.price / product.bulk_quantity)
    }
    return product.price // bulk price
}

// Initialize cart dengan existing qty dari database
onMounted(() => {
    if (props.categories && props.categories.length > 0) {
        props.categories.forEach(category => {
            if (category.products) {
                category.products.forEach(product => {
                    if (product.existing_qty > 0) {
                        cart.value[product.id] = {
                            qty: product.existing_qty,
                            price: product.price,
                            unit_type: 'bulk',
                            is_existing: true
                        }
                    }
                })
            }
        })
    }
})

// Update quantity
const updateQty = (productId, delta, price) => {
    const currentQty = cart.value[productId]?.qty || 0
    const newQty = currentQty + delta

    if (newQty <= 0) {
        delete cart.value[productId]
    } else {
        const unitType = getSelectedUnit(productId)
        cart.value[productId] = {
            qty: newQty,
            price: price, // harga satuan
            unit_type: unitType,
            is_existing: cart.value[productId]?.is_existing || false
        }
    }
}

// Get total quantity (existing + new)
const getTotalQty = (productId) => {
    return cart.value[productId]?.qty || 0
}

// Total items in cart
const totalItems = computed(() => {
    return Object.values(cart.value).reduce((sum, item) => sum + item.qty, 0)
})

// Total amount - PASTIKAN PERHITUNGAN BENAR
const totalAmount = computed(() => {
    return Object.values(cart.value).reduce((sum, item) => {
        // item.price adalah harga satuan, dikalikan qty
        return sum + (item.price * item.qty)
    }, 0)
})

// Toggle category
const toggleCategory = (categoryId) => {
    if (openCategoryId.value === categoryId) {
        openCategoryId.value = null
    } else {
        openCategoryId.value = categoryId
    }
}

// Check if category is open
const isCategoryOpen = (categoryId) => {
    return openCategoryId.value === categoryId
}

// Show product detail modal
const showDetail = (product) => {
    selectedProduct.value = product
    document.body.style.overflow = 'hidden'
}

// Close modal
const closeDetail = () => {
    selectedProduct.value = null
    document.body.style.overflow = 'auto'
}

// Add to cart from detail modal
const addToCartFromDetail = () => {
    if (selectedProduct.value) {
        const currentQty = getTotalQty(selectedProduct.value.id)
        if (currentQty < selectedProduct.value.stock) {
            updateQty(selectedProduct.value.id, 1, getProductPrice(selectedProduct.value))
        } else {
            alert('Stok tidak mencukupi!')
        }
        closeDetail()
    }
}

// Simpan offline
const saveOffline = async (orderData) => {
    const result = await saveOrderOffline(orderData)
    if (result.success) {
        alert('📱 Order disimpan secara offline. Akan di-sync otomatis saat online.')
        cart.value = {}
    } else {
        alert('❌ Gagal menyimpan order offline. Silakan coba lagi.')
    }
}

// Submit order
const submitOrder = async () => {
    if (totalItems.value === 0) {
        alert('Pilih minimal 1 produk terlebih dahulu')
        return
    }

    // Siapkan data items dengan informasi satuan lengkap
    const items = Object.entries(cart.value)
        .filter(([productId, item]) => {
            const product = props.categories
                .flatMap(c => c.products || [])
                .find(p => p.id === parseInt(productId))
            if (!product) return false
            // Kirim hanya jika ada tambahan quantity
            return item.qty > (product.existing_qty || 0)
        })
        .map(([productId, item]) => {
            const product = props.categories
                .flatMap(c => c.products || [])
                .find(p => p.id === parseInt(productId))
            const existingQty = product?.existing_qty || 0

            // Tentukan harga berdasarkan satuan yang dipilih
            const unitType = item.unit_type || 'bulk'
            let hargaSatuan = product.price // default bulk price
            let unitName = product.bulk_unit || 'Karton'

            if (unitType === 'retail') {
                hargaSatuan = product.retail_price || (product.price / product.bulk_quantity)
                unitName = product.retail_unit || 'pcs'
            } else {
                hargaSatuan = product.price // bulk price
                unitName = product.bulk_unit || 'Karton'
            }

            // Hitung tambahan qty
            const additionalQty = item.qty - existingQty

            // Subtotal = harga_satuan × qty
            const subtotal = hargaSatuan * additionalQty

            return {
                product_id: parseInt(productId),
                qty: additionalQty,
                qty_satuan: item.qty,
                price: subtotal,
                harga_satuan: hargaSatuan,
                unit_type: unitType,
                unit_name: unitName,
            }
        })

    if (items.length === 0) {
        alert('Tidak ada perubahan quantity')
        return
    }

    const orderData = {
        customer_id: props.customer.id,
        items: items,
        notes: ''
    }

    const url = props.existing_order_id
        ? `/sales/taking-order/order/${props.existing_order_id}/update`
        : '/sales/taking-order/order/store'

    const method = props.existing_order_id ? 'put' : 'post'

    try {
        if (isOnline.value) {
            router[method](url, orderData, {
                onSuccess: () => {
                    alert(props.existing_order_id ? '✅ Order berhasil diupdate!' : '✅ Order berhasil disimpan!')
                    cart.value = {}
                },
                onError: (errors) => {
                    console.error('Error:', errors)
                    if (!navigator.onLine || errors.offline) {
                        saveOffline(orderData)
                    } else {
                        alert('❌ Gagal menyimpan order: ' + (errors.message || 'Terjadi kesalahan'))
                    }
                }
            })
        } else {
            await saveOffline(orderData)
        }
    } catch (error) {
        console.error('Submit error:', error)
        await saveOffline(orderData)
    }
}
</script>

<style scoped>
button:active {
    transform: scale(0.95);
}

button:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.animate-fade-in-up {
    animation: fadeInUp 0.2s ease-out;
}

::-webkit-scrollbar {
    width: 4px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 5px;
}

::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 5px;
}

::-webkit-scrollbar-thumb:hover {
    background: #555;
}
</style>
