package com.unibuy.smartdevice.ui.dialog;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.unibuy.smartdevice.DialogAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.databinding.DialogMemberCardPickupBinding;
import com.unibuy.smartdevice.structure.ReportFreeGiftCodeStructure;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.HandlerMainCountdown;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.ui.FontendActivity;
import com.unibuy.smartdevice.external.StarCloudAPI;
import com.unibuy.smartdevice.exception.ErrorCode;
import com.unibuy.smartdevice.tools.Tools;

import java.util.HashMap;
import java.util.Map;

public class MemberCardPickupDialog extends DialogAbstract {
    public enum Option {
        TOAST(0),
        COUNTDOWN_CANCEL(1),
        SET_COUNTDOWN_TEXT(2),
        CHANGE_DISPATCH(3),
        ;

        private int option;

        public int getOption() {
            return option;
        }

        Option(int option) {
            this.option = option;
        }
    }

    public static final Map<Integer, Option> optionMap = new HashMap<>();
    static {
        for (Option option : Option.values()) {
            optionMap.put(option.getOption(), option);
        }
    }

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

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

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getContext(), getLogs()) {
            @Override
            protected void execute(Context context, int commandCode, String message) {
                Option option = optionMap.get(commandCode);
                if (option == null) return;
                
                switch (option) {
                    case TOAST:
                        super.execute(context, commandCode, message);
                        break;
                    case COUNTDOWN_CANCEL:
                        dialogCancel();
                        break;
                    case SET_COUNTDOWN_TEXT:
                        setButtonCancelText(Long.valueOf(message));
                        break;
                    case CHANGE_DISPATCH:
                        changeDispatch();
                        break;
                }
            }
        };
    }

    private DialogMemberCardPickupBinding binding;
    private CloseDialogOnThreadHandler closeDialogCountdown;
    private boolean isChangeDispatch = false;

    public MemberCardPickupDialog(Context context, HandlerMain srcHandlerMain) {
        super(context, srcHandlerMain);
    }

    private StringBuilder cardBuffer = new StringBuilder();

    @Override
    public boolean dispatchKeyEvent(android.view.KeyEvent event) {
        if (event.getAction() == android.view.KeyEvent.ACTION_DOWN) {
            int keyCode = event.getKeyCode();
            // 攔截數字鍵 (0-9)
            if (keyCode >= android.view.KeyEvent.KEYCODE_0 && keyCode <= android.view.KeyEvent.KEYCODE_9) {
                char number = (char) ('0' + (keyCode - android.view.KeyEvent.KEYCODE_0));
                cardBuffer.append(number);
                binding.editCardNo.setText(cardBuffer.toString());
                binding.editCardNo.setSelection(binding.editCardNo.getText().length());
                return true;
            }
            // 攔截 Enter 鍵
            if (keyCode == android.view.KeyEvent.KEYCODE_ENTER) {
                getLogs().info("MemberCardPickupDialog - Enter Key Detected!");
                String cardNo = cardBuffer.toString().trim();
                if (cardNo.isEmpty()) {
                    cardNo = binding.editCardNo.getText().toString().trim();
                }
                handleCardDetected(cardNo);
                cardBuffer.setLength(0); // 清空
                return true;
            }
            // 攔截刪除鍵
            if (keyCode == android.view.KeyEvent.KEYCODE_DEL) {
                if (cardBuffer.length() > 0) {
                    cardBuffer.deleteCharAt(cardBuffer.length() - 1);
                    binding.editCardNo.setText(cardBuffer.toString());
                    binding.editCardNo.setSelection(binding.editCardNo.getText().length());
                }
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onCreate(Context context) {
        binding = DialogMemberCardPickupBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        
        // 關鍵修正：清除 DialogAbstract 設定的 FLAG_NOT_FOCUSABLE，否則讀卡機訊號進不來
        if (getWindow() != null) {
            getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
            getWindow().setSoftInputMode(android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        }

        isChangeDispatch = true;
        cardBuffer.setLength(0);

        this.binding.buttonCancel.setOnClickListener(v -> dialogCancel());

        // 模擬測試按鈕
        this.binding.viewSimulateTap.setOnClickListener(v -> {
            cardBuffer.setLength(0);
            cardBuffer.append("0640741922");
            binding.editCardNo.setText(cardBuffer.toString());
            handleCardDetected(cardBuffer.toString());
        });

        // HID 讀卡邏輯
        binding.editCardNo.setText("");
        binding.editCardNo.requestFocus();
        
        binding.editCardNo.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE || 
                actionId == EditorInfo.IME_ACTION_UNSPECIFIED || 
                (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP)) {
                
                handleCardDetected(binding.editCardNo.getText().toString().trim());
                return true;
            }
            return false;
        });

        closeDialogCountdown = new CloseDialogOnThreadHandler(getHandlerMain());
        closeDialogCountdown.start(60);
    }

    private void handleCardDetected(String cardNo) {
        if (!cardNo.isEmpty()) {
            getLogs().info("MemberCardPickupDialog - Card Detected: " + cardNo);
            binding.editCardNo.setHint("正在驗證卡片...");
            binding.editCardNo.setText("");

            // 呼叫 B680 遠端驗證
            new StarCloudAPI(getHandlerMain(), getHandlerMain()).verifyStaffCard(cardNo, new StarCloudAPI.VerificationCallback() {
                @Override
                public void onSuccess(String codeId) {
                    getLogs().info("MemberCardPickupDialog - B680 Success, code_id: " + codeId);
                    
                    // ✅ 最後一道防線：出貨前即時檢查庫存
                    for (com.unibuy.smartdevice.structure.BuyStructure buy : MyApp.getInstance().getBuyList()) {
                        try {
                            com.unibuy.smartdevice.structure.SlotStructure liveSlot = 
                                MyApp.getInstance().getSlotData(buy.getField(), buy.getSlot());
                            if (liveSlot != null && liveSlot.getCount() <= 0) {
                                getLogs().info("庫存已歸零 slot=" + buy.getSlot() + "，取消出貨，返回銷售平台。");
                                getHandlerMain().start(getClass().getSimpleName(), Option.TOAST.getOption(), "商品已售罄，請重新選擇");
                                dialogCancel(); // 內部已清空 BuyList + dismiss
                                return;
                            }
                        } catch (Exception ignored) {}
                    }
                    
                    // 設定支付資訊
                    MyApp.getInstance().getReportFlowInfoData().setFlowType(41); // 員工卡
                    MyApp.getInstance().getReportFlowInfoData().setReportFlowId(cardNo);
                    MyApp.getInstance().getReportFlowInfoData().setFlowBarCode(cardNo);
                    
                    // 生成訂單編號 (避免後台找不到 order_no)
                    MyApp.getInstance().getReportFlowInfoData().setOrderId(Tools.generateTimeBasedUUID());
                    
                    // 設定交易總金額 (員工卡設為 0 元)
                    MyApp.getInstance().getReportFlowInfoData().setTotalPrice(0);
                    
                    // 儲存 code_id (用於 MQTT finalize)
                    MyApp.getInstance().getReportAccessCodeStructure().setAccessCodeId(codeId);
                    
                    // 跳轉到出貨
                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                        getHandlerMain().send(getClass().getSimpleName(), Option.CHANGE_DISPATCH.getOption(), "change dispatch");
                    }, 300);
                }

                @Override
                public void onFailure(String message) {
                    getLogs().error(ErrorCode.NETWORK_UNKNOWN_ERROR, "MemberCardPickupDialog - B680 Failed: " + message);
                    binding.editCardNo.setText("");
                    binding.editCardNo.setHint(message);
                    cardBuffer.setLength(0);
                    getHandlerMain().start(getClass().getSimpleName(), Option.TOAST.getOption(), message);
                }
            });
        }
    }


    public void changeDispatch() {
        if (isChangeDispatch) {
            isChangeDispatch = false;
            closeDialogCountdown.shutdown();
            changeDialog(DispatchDialog.class);
        }
    }

    public void dialogCancel() {
        if (this.isShowing()) {
            MyApp.getInstance().setReportFreeGiftCodeStructure(new ReportFreeGiftCodeStructure("", 0, "", 0, 0, ""));
            getSrcHandlerMain().start(getClass().getSimpleName(), FontendActivity.Option.STOP_COUNTDOWN.getOption(), "");
            closeDialogCountdown.shutdown();
            MyApp.getInstance().getBuyList().clear();
            cancel();
        }
    }

    public void setButtonCancelText(long countdown) {
        binding.buttonCancel.setText("取消(" + countdown + ")");
    }

    public class CloseDialogOnThreadHandler extends HandlerMainCountdown {
        public CloseDialogOnThreadHandler(HandlerMain handlerMain) {
            super(handlerMain);
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void close(HandlerMain handlerMain) {
            if (MemberCardPickupDialog.this.isShowing()) {
                handlerMain.start(getClass().getSimpleName(), Option.COUNTDOWN_CANCEL.getOption(), "countdown cancel");
            }
        }

        @Override
        protected void execute(long countdown, HandlerMain handlerMain) {
            handlerMain.start(getClass().getSimpleName(), Option.SET_COUNTDOWN_TEXT.getOption(), String.valueOf(countdown));
        }

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