package com.unibuy.v2.vm

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.blankj.utilcode.util.ToastUtils
import com.unibuy.smartdevice.MyApp
import com.unibuy.smartdevice.R
import com.unibuy.smartdevice.structure.BuyStructure
import com.unibuy.smartdevice.structure.SlotStructure
import com.unibuy.v2.UnibuyHelper
import com.unibuy.v2.bean.CartOperationResult

/**
 * 多品項購物車 ViewModel（自 Luzui v2 移植）。
 *
 * 與 Luzui 版差異：
 * - 移除 updateLocalGoods()：Luzui 用 SlotField.FLOWER + SlotsDao 在出貨後扣本地庫存，
 *   TaiwanStar 為 VMC 貨道機、扣庫存由既有 DispatchDialog / MQTT 結案負責，購物車不重複處理。
 * - 寫死中文改用 R.string.cart_max_items。
 */
class CartViewModel : ViewModel() {
    private val _cartItems = MutableLiveData<List<SlotStructure>>(emptyList())
    val cartItems: LiveData<List<SlotStructure>> = _cartItems
    val freeGoods: MutableList<BuyStructure> = mutableListOf()

    /** 把購物車內容寫入 MyApp.buyList，交棒給既有結帳鏈（BuyDialog → 付款 → DispatchDialog → MQTT）。 */
    fun convertToBuyStructure() {
        MyApp.getInstance().apply {
            buyList.clear()
            // 1. 免費商品（來店禮；General 不做時恆空）
            buyList += freeGoods
            // 2. 購物車商品：依可賣貨道把數量拆成多筆 count=1，規避 VMC 出貨狀態機不支援單筆 quantity>1
            //    （出完第 1 個後不會自動觸發下一次出貨，會卡 40 秒看門狗）。拆道邏輯集中在 MyApp.allocateBuyStructures。
            buyList += UnibuyHelper.getCartViewModel()
                .getCartItemsSnapshot()
                .flatMap { cartItem ->
                    allocateBuyStructures(cartItem, cartItem.cartSelectedCount)
                }
        }
    }

    /** 購物車最多 3 件（全車總件數上限） */
    fun hasMinimumCartItems(): Boolean {
        return getAllCartItems().totalCount >= 3
    }

    fun getCartItemsSnapshot(): List<SlotStructure> = _cartItems.value ?: emptyList()

    // 添加商品到購物車（以 field + slot + productID 唯一識別）
    fun addToCart(slot: SlotStructure): CartOperationResult {
        // 效期過期商品一律暫不販售，禁止加入購物車
        if (slot.isExpired) {
            ToastUtils.showLong(R.string.product_expired)
            return createResult(null)
        }
        val currentItems = _cartItems.value?.toMutableList() ?: mutableListOf()
        val item = currentItems.find {
            it.field == slot.field &&
                    it.slot == slot.slot &&
                    it.product?.productID == slot.product?.productID
        }

        return if (item == null) {
            if (hasMinimumCartItems()) {
                ToastUtils.showLong(R.string.cart_max_items)
                return createResult(null)
            }
            slot.cartSelectedCount = 1
            val newList = currentItems.toMutableList().apply { add(slot) }
            _cartItems.value = newList
            createResult(slot)
        } else if (item.cartSelectedCount >= item.count) {
            ToastUtils.showLong(R.string.cart_out_of_stock)
            createResult(item)
        } else {
            if (UnibuyHelper.getCartViewModel().hasMinimumCartItems()) {
                ToastUtils.showLong(R.string.cart_max_items)
                createResult(item)
            } else {
                item.cartSelectedCount++
                _cartItems.value = currentItems
                createResult(item)
            }
        }
    }

    // 從購物車減少一件
    fun removeFromCart(slot: SlotStructure): CartOperationResult {
        val currentItems = _cartItems.value?.toMutableList() ?: mutableListOf()
        val item = currentItems.find {
            it.field == slot.field &&
                    it.slot == slot.slot &&
                    it.product?.productID == slot.product?.productID
        } ?: return CartOperationResult(0, 0, 0, 0)

        return if (item.cartSelectedCount > 1) {
            item.cartSelectedCount--
            _cartItems.value = currentItems
            createResult(item)
        } else {
            ToastUtils.showLong(R.string.cart_cannot_decrease)
            createResult(item)
        }
    }

    // 清空購物車
    fun clearCart(): CartOperationResult {
        val result = createResult(null)
        _cartItems.value = emptyList()
        return result.copy(
            totalPrice = 0,
            totalCount = 0,
            currentItemCount = 0,
            currentItemPrice = 0
        )
    }

    fun createResult(item: SlotStructure?): CartOperationResult {
        val currentCount = item?.cartSelectedCount ?: 0
        val currentPrice = (item?.product?.realPrice ?: 0) * currentCount
        val currentItems = _cartItems.value ?: emptyList()

        return CartOperationResult(
            totalPrice = currentItems.sumOf { it.cartSelectedCount * (it.product?.realPrice ?: 0) },
            totalCount = currentItems.sumOf { it.cartSelectedCount },
            currentItemCount = currentCount,
            currentItemPrice = currentPrice
        )
    }

    // 移除整筆商品
    fun removeItemFromCart(slot: SlotStructure): CartOperationResult {
        val currentItems = _cartItems.value?.toMutableList() ?: mutableListOf()
        val productIdToRemove = slot.product?.productID
        if (productIdToRemove != null) {
            currentItems.removeAll { item ->
                item.product?.productID == productIdToRemove
            }
        }
        _cartItems.value = currentItems
        return getAllCartItems()
    }

    fun getAllCartItems(): CartOperationResult {
        val currentItems = _cartItems.value ?: emptyList()
        return CartOperationResult(
            totalPrice = currentItems.sumOf { it.cartSelectedCount * (it.product?.realPrice ?: 0) },
            totalCount = currentItems.sumOf { it.cartSelectedCount },
            currentItemCount = 0,
            currentItemPrice = 0
        )
    }
}
