package com.unibuy.smartdevice.ui.tools;

import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import com.unibuy.smartdevice.R;
import com.unibuy.smartdevice.tools.SimpleCashAcceptorHandler;

public class CashMachineSettings extends AppCompatActivity implements View.OnClickListener {

    // --- 鈔票機元件 (Bill Machine Components) ---
    private Button btnConnectBill, btnDisconnectBill;
    private Button btnShowBillStatus, btnStartAccept, btnCancelAccept;
    private Button btnDispenseBill;
    private TextView tvBillStatusDisplay;
    private EditText etBillDispenseCount;

    // --- 硬幣機元件 (Coin Machine Components) ---
    private Button btnConnectCoin, btnDisconnectCoin;
    private Button btnShowCoinCount;
    private TextView tvCoin50Count, tvCoin10Count, tvCoin5Count, tvCoin1Count;
    private EditText etCoinDispense50Count, etCoinDispense10Count, etCoinDispense5Count, etCoinDispense1Count;
    private Button btnDispense50, btnDispense10, btnDispense5, btnDispense1;

    private Button leave;
    /// ////

    SimpleCashAcceptorHandler simpleCashAcceptorHandler;
    int fourthValueDecimal;

    private int coin50_count;
    private int coin10_count;
    private int coin5_count;
    private int coin1_count;
    private int note100_count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_cash_machine_settings);

        initViews();
        setupListeners();
        setDefaultCoinCounts();

        // 實例化 Handler，並傳入事件監聽器
        simpleCashAcceptorHandler = new SimpleCashAcceptorHandler(this,
                event -> new Handler(Looper.getMainLooper()).post(() -> handleMdbEvent(event)));

        // 啟動一個新執行緒來處理連線
        // 啟動一個新執行緒來處理連線
        new Thread(() -> {
            String result = simpleCashAcceptorHandler.connect();
            new Handler(Looper.getMainLooper()).post(() -> {
                // Toast.makeText(getCtx(), result, Toast.LENGTH_LONG).show();
                if ("成功連接到 USB 轉接器！".equals(result)) {
                    messageShow("請稍後", 3000);

                    simpleCashAcceptorHandler.startReading();
                    // 依序發送初始化指令
                    sendMdbCommand("0CFFFFFFFF", simpleCashAcceptorHandler, 1000, () -> {
                        sendMdbCommand("34FFFFFFFF", simpleCashAcceptorHandler, 500, () -> {
                            sendMdbCommand("370100000002", simpleCashAcceptorHandler, 500, () -> {
                                sendMdbCommand("3703", simpleCashAcceptorHandler, 500, () -> {
                                    sendMdbCommand("3704000003000000000000000000000000000000",
                                            simpleCashAcceptorHandler, 500, () -> {
                                                sendMdbCommand("3705", simpleCashAcceptorHandler, 500, () -> {
                                                    sendMdbCommand("0A", simpleCashAcceptorHandler, 500, null);
                                                });
                                            });
                                });
                            });
                        });
                    });
                }
            });
        }).start();

    }

    /**
     * 初始化所有 Views (findViewById)
     */
    private void initViews() {
        // 鈔票機
        btnConnectBill = findViewById(R.id.btn_connect_bill);
        btnDisconnectBill = findViewById(R.id.btn_disconnect_bill);
        btnShowBillStatus = findViewById(R.id.btn_show_bill_status);
        btnStartAccept = findViewById(R.id.btn_start_accept);
        btnCancelAccept = findViewById(R.id.btn_cancel_accept);
        btnDispenseBill = findViewById(R.id.btn_dispense_bill);
        tvBillStatusDisplay = findViewById(R.id.tv_bill_status_display);
        etBillDispenseCount = findViewById(R.id.et_bill_dispense_count);

        // 硬幣機
        btnConnectCoin = findViewById(R.id.btn_connect_coin);
        btnDisconnectCoin = findViewById(R.id.btn_disconnect_coin);
        btnShowCoinCount = findViewById(R.id.btn_show_coin_count);
        tvCoin50Count = findViewById(R.id.tv_coin_50_count);
        tvCoin10Count = findViewById(R.id.tv_coin_10_count);
        tvCoin5Count = findViewById(R.id.tv_coin_5_count);
        tvCoin1Count = findViewById(R.id.tv_coin_1_count);
        etCoinDispense50Count = findViewById(R.id.et_coin_dispense_50_count);
        etCoinDispense10Count = findViewById(R.id.et_coin_dispense_10_count);
        etCoinDispense5Count = findViewById(R.id.et_coin_dispense_5_count);
        etCoinDispense1Count = findViewById(R.id.et_coin_dispense_1_count);
        btnDispense50 = findViewById(R.id.btn_dispense_50);
        btnDispense10 = findViewById(R.id.btn_dispense_10);
        btnDispense5 = findViewById(R.id.btn_dispense_5);
        btnDispense1 = findViewById(R.id.btn_dispense_1);
        leave = findViewById(R.id.leave);

    }

    /**
     * 設定所有按鈕的點擊監聽器
     */
    private void setupListeners() {
        // 鈔票機
        btnConnectBill.setOnClickListener(this);
        btnDisconnectBill.setOnClickListener(this);
        btnShowBillStatus.setOnClickListener(this);
        btnStartAccept.setOnClickListener(this);
        btnCancelAccept.setOnClickListener(this);
        btnDispenseBill.setOnClickListener(this);

        // 硬幣機
        btnConnectCoin.setOnClickListener(this);
        btnDisconnectCoin.setOnClickListener(this);
        btnShowCoinCount.setOnClickListener(this);
        btnDispense50.setOnClickListener(this);
        btnDispense10.setOnClickListener(this);
        btnDispense5.setOnClickListener(this);
        btnDispense1.setOnClickListener(this);
        leave.setOnClickListener(this);

    }

    /**
     * 設定硬幣機初始模擬數量
     */
    private void setDefaultCoinCounts() {

        tvCoin50Count.setText("50元數量:"); // 假設初始有 10 個 50 元
        tvCoin10Count.setText("10元數量:");
        tvCoin5Count.setText("5元數量:");
        tvCoin1Count.setText("1元數量:");
    }

    /**
     * 統一處理所有按鈕的點擊事件
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_connect_bill) {
            showToast("嘗試連接鈔票機...");

            sendMdbCommand("34FFFFFFFF", simpleCashAcceptorHandler, 0, () -> {
            });

        } else if (id == R.id.btn_disconnect_bill) {
            showToast("嘗試斷開鈔票機...");

            sendMdbCommand("3400000000", simpleCashAcceptorHandler, 0, () -> {
            });

        } else if (id == R.id.btn_show_bill_status) {
            showToast("鈔票機狀態已更新");

            sendMdbCommand("3705", simpleCashAcceptorHandler, 600, () -> {

            });

        } else if (id == R.id.btn_start_accept) {
            showToast("鈔票機已啟動收鈔模式 (循環區)");

            sendMdbCommand("34FFFFFFFF", simpleCashAcceptorHandler, 0, () -> {

            });

        } else if (id == R.id.btn_cancel_accept) {
            showToast("鈔票機已取消收鈔");

            sendMdbCommand("3400000000", simpleCashAcceptorHandler, 0, () -> {
            });

        } else if (id == R.id.btn_dispense_bill) {
            /// 退鈔
            dispenseBillAction();

        } else if (id == R.id.btn_connect_coin) {
            showToast("嘗試連接硬幣機...");

            sendMdbCommand("0CFFFFFFFF", simpleCashAcceptorHandler, 0, () -> {
            });

        } else if (id == R.id.btn_disconnect_coin) {
            showToast("嘗試斷開硬幣機...");

            sendMdbCommand("0C00000000", simpleCashAcceptorHandler, 0, () -> {
            });

        } else if (id == R.id.btn_show_coin_count) {
            showToast("嘗試更新硬幣數量...");
            sendMdbCommand("0A", simpleCashAcceptorHandler, 0, () -> {

            });

        } else if (id == R.id.btn_dispense_50) {
            // 掉出硬幣
            dispenseCoinAction(50, etCoinDispense50Count);

        } else if (id == R.id.btn_dispense_10) {
            // 掉出硬幣
            dispenseCoinAction(10, etCoinDispense10Count);
        } else if (id == R.id.btn_dispense_5) {
            // 掉出硬幣
            dispenseCoinAction(5, etCoinDispense5Count);
        } else if (id == R.id.btn_dispense_1) {
            // 掉出硬幣
            dispenseCoinAction(1, etCoinDispense1Count);
        } else if (id == R.id.leave) {
            sendMdbCommand("3400000000", simpleCashAcceptorHandler, 0, () -> {
            });
            sendMdbCommand("0C00000000", simpleCashAcceptorHandler, 300, () -> {
                new Handler(Looper.getMainLooper()).postDelayed(() -> simpleCashAcceptorHandler.close(), 1000);

                finish();

            });

        }

    }

    /**
     * 處理鈔票退出的操作邏輯
     */
    private void dispenseBillAction() {
        String countStr = etBillDispenseCount.getText().toString();
        if (TextUtils.isEmpty(countStr)) {
            showToast("請輸入要退出的張數");
            return;
        }

        try {
            int count = Integer.parseInt(countStr);
            if (count > 0) {
                showToast("鈔票機嘗試退出 " + count + " 張鈔票...");

                sendMdbCommand("3400000000", simpleCashAcceptorHandler, 0, () -> {
                    sendMdbCommand("370100000002", simpleCashAcceptorHandler, 1000, () -> {
                        sendMdbCommand("3703", simpleCashAcceptorHandler, 600, () -> {
                            sendMdbCommand("3704000003000000000000000000000000000000", simpleCashAcceptorHandler, 1000,
                                    () -> {
                                        sendMdbCommand("370600000" + count, simpleCashAcceptorHandler, 1000, () -> {

                                        });
                                    });
                        });

                    });

                });

            } else {
                showToast("張數必須大於 0");
            }
        } catch (NumberFormatException e) {
            showToast("請輸入有效的數字");
        }
    }

    /**
     * 處理硬幣掉出的操作邏輯
     * 
     * @param denomination 硬幣面額 (50, 10, 5, 1)
     * @param editText     輸入的張數欄位
     */
    private void dispenseCoinAction(int denomination, EditText editText) {
        String countStr = editText.getText().toString();
        if (TextUtils.isEmpty(countStr)) {
            showToast("請輸入要掉出的 " + denomination + " 元硬幣數量");
            return;
        }

        try {
            int count = Integer.parseInt(countStr);
            if (count > 0) {
                showToast("硬幣機嘗試掉出 " + count + " 個 " + denomination + " 元硬幣...");

                // *** 關鍵修正：將十進制 count 轉換為兩位十六進制字串 ***
                String hexCount = String.format("%01X", count);

                if (denomination == 1) {
                    sendMdbCommand("0D" + hexCount + "0", simpleCashAcceptorHandler, 1000, () -> {
                    });

                } else if (denomination == 5) {
                    sendMdbCommand("0D" + hexCount + "1", simpleCashAcceptorHandler, 1000, () -> {
                    });

                } else if (denomination == 10) {
                    sendMdbCommand("0D" + hexCount + "2", simpleCashAcceptorHandler, 1000, () -> {
                    });

                } else if (denomination == 50) {
                    sendMdbCommand("0D" + hexCount + "4", simpleCashAcceptorHandler, 1000, () -> {
                    });

                }

            } else {
                showToast("數量必須大於 0");
            }
        } catch (NumberFormatException e) {
            showToast("請輸入有效的數字");
        }
    }

    /**
     * 簡化 Toast 訊息顯示
     * 
     * @param message 要顯示的訊息
     */
    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    public byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    private void sendMdbCommand(final String hexCommand, final SimpleCashAcceptorHandler handler) {
        new Thread(() -> {
            try {
                byte[] command = hexStringToByteArray(hexCommand);
                int bytesWritten = handler.writeData(command);
                if (bytesWritten > 0) {
                    new Handler(Looper.getMainLooper()).post(() -> {
                    });
                } else {
                    new Handler(Looper.getMainLooper()).post(() -> {
                    });
                }
            } catch (Exception e) {
                new Handler(Looper.getMainLooper()).post(() -> {
                });
            }
        }).start();
    }

    private void sendMdbCommand(String command, SimpleCashAcceptorHandler handler, int delay, Runnable onComplete) {
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            sendMdbCommand(command, handler);
            if (onComplete != null) {
                onComplete.run();
            }
        }, delay);
    }

    // 接收設備的回應
    private void handleMdbEvent(String event) {

        Toast.makeText(this, "收到事件: " + event, Toast.LENGTH_LONG).show();
        if (event.length() >= 5) {
            String code = event.substring(0, 5);
            switch (code) {
                case "08 54": // 50 元

                    break;

                case "08 52": // 10 元

                    break;
                case "08 51":

                    break;
                case "08 50":

                    break;
                case "30 90": // 100元

                    new Handler(Looper.getMainLooper())
                            .postDelayed(() -> sendMdbCommand("3503", simpleCashAcceptorHandler), 800);

                    break;

                case "30 92": // 500元

                    new Handler(Looper.getMainLooper())
                            .postDelayed(() -> sendMdbCommand("3501", simpleCashAcceptorHandler), 1300);

                    break;

                case "30 93": // 1000元
                    new Handler(Looper.getMainLooper())
                            .postDelayed(() -> sendMdbCommand("3501", simpleCashAcceptorHandler), 1300);
                    break;

            }

            /// 查詢循環機裡面紙鈔
            if (event != null && event.trim().split(" ").length == 35) {
                String[] parts = event.trim().split(" ");
                boolean isValidFormat = true;
                for (String part : parts) {
                    if (part.length() != 2) {
                        isValidFormat = false;
                        break;
                    }
                }
                if (isValidFormat) {
                    try {
                        String fourthValueHex = parts[3];
                        fourthValueDecimal = Integer.parseInt(fourthValueHex, 16);
                        if (fourthValueDecimal > 0 && fourthValueDecimal <= 30) {
                            // Toast.makeText(getCtx(), "循環機裡面紙鈔: " + fourthValueDecimal,
                            // Toast.LENGTH_LONG).show();
                            note100_count = fourthValueDecimal;

                            tvBillStatusDisplay.setText("循環區裡面百鈔數量" + note100_count);

                        } else {
                            Log.d("MDB_EVENT", "第四個位置數值為: " + fourthValueDecimal + "，超出預期範圍。");
                            note100_count = 0;
                            tvBillStatusDisplay.setText("循環區裡面百鈔數量" + note100_count);
                        }
                        return;
                    } catch (NumberFormatException e) {
                        Log.e("MDB_EVENT", "十六進制轉換失敗，不處理此事件: " + e.getMessage());
                    }
                }
            }

            /// 查詢硬幣機裡面硬幣
            if (event != null && event.trim().split(" ").length == 19) {
                String[] parts = event.trim().split(" ");
                boolean isValidFormat = true;
                for (String part : parts) {
                    if (part.length() != 2) {
                        isValidFormat = false;
                        break;
                    }
                }
                if (isValidFormat) {
                    try {
                        int oneYuanCount = Integer.parseInt(parts[2], 16);
                        int fiveYuanCount = Integer.parseInt(parts[3], 16);
                        int tenYuanCount = Integer.parseInt(parts[4], 16);
                        // 50元對應的是 Type 4，因此在 MDB 0A 回傳陣列中位於第 7 個位置 (index 6)
                        int fiftyYuanCount = Integer.parseInt(parts[6], 16);
                        coin1_count = oneYuanCount;
                        coin5_count = fiveYuanCount;
                        coin10_count = tenYuanCount;
                        coin50_count = fiftyYuanCount;

                        tvCoin50Count.setText("50元數量:" + coin50_count); // 假設初始有 10 個 50 元
                        tvCoin10Count.setText("10元數量:" + coin10_count);
                        tvCoin5Count.setText("5元數量:" + coin5_count);
                        tvCoin1Count.setText("1元數量:" + coin1_count);

                        return;
                    } catch (NumberFormatException e) {
                        Log.e("MDB_EVENT", "十六進制轉換失敗，不處理此事件: " + e.getMessage());
                    }
                }
            }
        }
        Log.d("MDB_EVENT", "收到事件: " + event);
        // Toast.makeText(getCtx(), "收到事件: " + event, Toast.LENGTH_LONG).show();
    }

    void messageShow(String massage, int second) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View dialogView = View.inflate(this, R.layout.mydialog1, null);
        TextView t1 = dialogView.findViewById(R.id.text01);
        TextView t2 = dialogView.findViewById(R.id.text02);
        t1.setText("提示!");
        t2.setText(massage);
        dialog.setView(dialogView);
        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT);
        }
        dialog.show();
        if (second > 0)
            new Handler().postDelayed(dialog::dismiss, second);
    }

}
