package com.unibuy.v2.ui;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;

import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.unibuy.smartdevice.FragmentAbstract;
import com.unibuy.smartdevice.R;
import com.unibuy.smartdevice.databinding.FragmentShoppingCartBinding;
import com.unibuy.smartdevice.structure.SlotStructure;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.ui.FontendActivity;
import com.unibuy.v2.UnibuyHelper;
import com.unibuy.v2.adapter.CartOperationAdapter;
import com.unibuy.v2.bean.CartOperationResult;
import com.unibuy.v2.utils.SafeCountdownUtil;

import java.util.List;

/**
 * General flavor 多品項購物車 Fragment（自 Luzui v2 移植並適配）。
 *
 * 與 Luzui 差異：
 * - 移除 HttpAPI / DialogXManager / FlowerFragment / 格子機相關邏輯。
 * - 「加購」回 VMC 商品列表；「結帳」改為 convertToBuyStructure() + SaleFlowHandler.onBuyRequested()
 *   交棒給 TaiwanStar 既有結帳鏈（BuyDialog → 付款 → DispatchDialog → MQTT 結案）。
 * - 移除 MyApp.setShoppingCartFragmentInstance（TaiwanStar 無此 API）。
 */
public class ShoppingCartFragment extends FragmentAbstract {
    private FragmentShoppingCartBinding binding;
    private CartOperationAdapter cartAdapter;
    private CartOperationResult allCartItems;
    private SafeCountdownUtil countdownUtil;

    private static final int DEBOUNCE_DURATION = 500;
    private static final int COUNTDOWN_DURATION = 180;

    /** 回傳當前倒數秒數（未初始化回 -1）。 */
    public int getCurrentCountdownSeconds() {
        if (countdownUtil != null) {
            return countdownUtil.getCurrentSeconds();
        }
        return -1;
    }

    @Override
    protected String setName() {
        return getString(R.string.shopping_cart_title);
    }

    @Override
    protected Context setCtx() {
        return getContext();
    }

    @Override
    protected Class<?> setCls() {
        return getClass();
    }

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getCtx(), getLogs()) {
            @Override
            protected void execute(Context context, int commandCode, String message) {
                // 購物車本身不需處理額外指令
            }
        };
    }

    public ShoppingCartFragment() {
        super(null);
    }

    public ShoppingCartFragment(HandlerMain srcHandlerMain) {
        super(srcHandlerMain);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentShoppingCartBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setupUI();
    }

    private void setupUI() {
        setupCartRecyclerView();
        setupClickListeners();
        refreshTitleView();
        initCountdownUtil();
    }

    private void initCountdownUtil() {
        if (countdownUtil == null) {
            countdownUtil = new SafeCountdownUtil(getViewLifecycleOwner().getLifecycle());
            countdownUtil.setCountdownListener(new SafeCountdownUtil.CountdownListener() {
                @Override
                public void onTick(int seconds) {
                    updateCountdownText(seconds);
                }

                @Override
                public void onFinish() {
                    // isAdded() 在 onSaveInstanceState 後仍為 true，無法擋住背景 commit；
                    // 改以 lifecycle 是否達 STARTED 為準（最終 commit 防呆在 FontendActivity）。
                    if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)
                            && getActivity() != null) {
                        getActivity().runOnUiThread(() -> clearCartAndBack());
                    }
                }
            });
        }
    }

    private void updateCountdownText(int seconds) {
        if (!isAdded() || getActivity() == null) {
            return;
        }
        getActivity().runOnUiThread(() -> {
            if (binding != null && binding.cancelText != null) {
                binding.cancelText.setText(getString(R.string.cart_cancel_button_format, seconds));
            }
        });
    }

    private void handleCartItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        try {
            SlotStructure slot = (SlotStructure) adapter.getData().get(position);
            int viewId = view.getId();
            if (viewId == R.id.buttonMinus) {
                UnibuyHelper.INSTANCE.getCartViewModel().removeFromCart(slot);
                adapter.notifyItemChanged(position);
                countdownReset(); // 使用者調整數量＝有互動，續命 180 秒倒數
            } else if (viewId == R.id.buttonPlus) {
                UnibuyHelper.INSTANCE.getCartViewModel().addToCart(slot);
                adapter.notifyItemChanged(position);
                countdownReset(); // 使用者調整數量＝有互動，續命 180 秒倒數
            } else if (viewId == R.id.buttonWaste) {
                UnibuyHelper.INSTANCE.getCartViewModel().removeItemFromCart(slot);
                adapter.remove(position);
                // 購物車清空後返回 VMC 商品列表
                if (UnibuyHelper.INSTANCE.getCartViewModel().getCartItemsSnapshot().isEmpty()) {
                    backToVmc();
                } else {
                    countdownReset(); // 還有商品，視為有互動，續命 180 秒倒數
                }
            }
            // layout_product / image_product 的商品詳情 popup 屬 Luzui DialogXManager，General 不採用
            refreshTitleView();
        } catch (Exception e) {
            ToastUtils.showLong(getString(R.string.data_error));
            e.printStackTrace();
        }
    }

    private void setupClickListeners() {
        // 加購商品：回到 VMC 商品列表繼續挑選
        ClickUtils.applySingleDebouncing(binding.addMoreItemsButton, DEBOUNCE_DURATION, v -> backToVmc());

        // 前往結帳：寫入 buyList 後交棒給既有結帳鏈
        ClickUtils.applySingleDebouncing(binding.confirmButton, DEBOUNCE_DURATION, v -> {
            if (UnibuyHelper.INSTANCE.getCartViewModel().getCartItemsSnapshot().isEmpty()) {
                ToastUtils.showLong(getString(R.string.cart_cannot_decrease));
                return;
            }
            UnibuyHelper.INSTANCE.getCartViewModel().convertToBuyStructure();
            FontendActivity activity = getFontendActivity();
            if (activity != null && activity.getSaleFlowHandler() != null) {
                activity.getSaleFlowHandler().onBuyRequested();
            }
        });

        // 取消：清空購物車並返回 VMC
        ClickUtils.applySingleDebouncing(binding.cancelButton, DEBOUNCE_DURATION, v -> clearCartAndBack());
    }

    private void setupCartRecyclerView() {
        List<SlotStructure> cartItems = UnibuyHelper.INSTANCE.getCartViewModel().getCartItemsSnapshot();
        cartAdapter = new CartOperationAdapter(R.layout.recycler_cart_operation, cartItems);
        cartAdapter.setOnItemChildClickListener(this::handleCartItemClick);
        binding.shoppingCartRecyclerView.setAdapter(cartAdapter);
    }

    private void refreshTitleView() {
        allCartItems = UnibuyHelper.INSTANCE.getCartViewModel().getAllCartItems();
        binding.totalItemsTextView.setText(getString(R.string.total_items_format, allCartItems.getTotalCount()));
        binding.totalAmountTextView.setText(getString(R.string.total_amount_format, allCartItems.getTotalPrice()));
        
        if (UnibuyHelper.INSTANCE.getCartViewModel().hasMinimumCartItems()) {
            binding.maxItemsWarningTextView.setVisibility(View.VISIBLE);
        } else {
            binding.maxItemsWarningTextView.setVisibility(View.GONE);
        }
    }

    /** 清空購物車並切回 VMC 商品列表。 */
    private void clearCartAndBack() {
        UnibuyHelper.INSTANCE.getCartViewModel().clearCart();
        backToVmc();
    }

    private void backToVmc() {
        FontendActivity activity = getFontendActivity();
        if (activity != null) {
            activity.backToVmc();
        }
    }

    @Nullable
    private FontendActivity getFontendActivity() {
        if (getActivity() instanceof FontendActivity) {
            return (FontendActivity) getActivity();
        }
        return null;
    }

    @Override
    public void startOnSwitchFragment() {
        setupUI();
        countdownUtil.startOrReset(COUNTDOWN_DURATION);
    }

    @Override
    public void stopOnSwitchFragment() {
        if (countdownUtil != null) {
            countdownUtil.stop();
        }
    }

    public void countdownReset() {
        countdownUtil.startOrReset(COUNTDOWN_DURATION);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
