package com.unibuy.smartdevice.ui.recycler;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.unibuy.smartdevice.AppCompatActivityAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.R;
import com.unibuy.smartdevice.controller.DevController;
import com.unibuy.smartdevice.databinding.RecyclerDialogBuyListBinding;
import com.unibuy.smartdevice.devices.PortTools;
import com.unibuy.smartdevice.devices.SlotField;
import com.unibuy.smartdevice.exception.Logs;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.exception.LogsNoSuchElementException;
import com.unibuy.smartdevice.structure.BuyStructure;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.ui.dialog.BuyDialog;
import com.unibuy.smartdevice.ui.dialog.DispatchDialog;
import com.unibuy.smartdevice.ui.tools.ImageGlide;
import com.unibuy.smartdevice.utils.LanguageHelper;

import java.util.List;

public class RecyclerDialogBuyListAdpter extends RecyclerView.Adapter<RecyclerDialogBuyListAdpter.ViewHolder> {
    private Logs logs;
    private Context context;
    private final List<BuyStructure> buyList;
    private HandlerMain handlerMain;
    private boolean haveThings,doorError;

    public RecyclerDialogBuyListAdpter(Context context, List<BuyStructure> buyList, HandlerMain handlerMain) {
        this.logs = new Logs(this.getClass());
        this.context = context;
        this.buyList = buyList;
        this.handlerMain = handlerMain;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        RecyclerDialogBuyListBinding binding;

        public ViewHolder(@NonNull RecyclerDialogBuyListBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 使用 ViewBinding 來綁定佈局
        RecyclerDialogBuyListBinding binding = RecyclerDialogBuyListBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);

        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        logs.info("position:" + position);
        // 讀取最後設定語言的設定
//        LanguageHelper.applySavedLanguage(context);
        haveThings = false;

        BuyStructure buyProduct = buyList.get(position);
        holder.binding.textPosition.setText(String.valueOf(position));
        String productID = buyProduct.getProduct().getProductID();
        if (!productID.isEmpty() && !productID.equals("?")) {
            holder.binding.textProductName.setText(buyProduct.getProduct().getProductName());
            //多國語的判斷
//            String currentLang = LanguageHelper.getSavedLanguage(context);
//            switch (currentLang) {
//                case "tw":
//                    holder.binding.textProductName.setText(buyProduct.getProduct().getProductName());
//                    break;
//                case "en":
//                    holder.binding.textProductName.setText(buyProduct.getProduct().getProductNameEn());
//                    break;
//                case "ja":
//                    holder.binding.textProductName.setText(buyProduct.getProduct().getProductNameJp());
//                    break;
//            }
        } else {
            holder.binding.textProductName.setText(context.getString(R.string.click_select_product));//點我選擇商品
        }
//        holder.binding.textDelete.setOnClickListener(new textDeleteOnClickListener(position));
        String urlString = buyProduct.getProduct().getProductImg();
        try {
            new ImageGlide(context).fileload(urlString, holder.binding.imageProductPicture);
        } catch (LogsEmptyException e) {
            this.logs.warning(e);
        }
        int machinePrice = buyProduct.getProduct().getMachinePrice();
        int sellingPrice = buyProduct.getProduct().getSellingPrice();
        int memberPrice = buyProduct.getProduct().getMemberPrice();

        int slotUpperLimit = buyProduct.getProduct().getSlotUpperLimit();
        int count = buyProduct.getCount();
        String unit = "";

        try {
            SlotField slotField = SlotField.getSlotField(buyProduct.getField());
            switch (slotField) {
                case VMC:
                    unit = buyProduct.isMarketingPlan() ? context.getString(R.string.group) : "";//組
                    break;
                case ELECTRIC:
                    unit = buyProduct.isMarketingPlan() ? context.getString(R.string.group) : context.getString(R.string.hour);//組，小時
                    break;
            }
        } catch (LogsEmptyException e) {
            logs.warning(e);
        }

        int price = machinePrice > 0? machinePrice: sellingPrice;

        if (buyProduct.isFreeGift()) {
            holder.binding.textPrice.setText(context.getString(R.string.donate));//贈
        } else {
            holder.binding.textPrice.setText("NT $" + price);
        }
        holder.binding.productSlot.setText(String.format("%03d", buyProduct.getSlot()));

        /* 這裡取出預購買的商品剩餘數量 */
        int remainingcount = 0;
        for(int j = 0; j < MyApp.getInstance().getSlotList(0).size();j++) {
            if(buyProduct.getProduct().getProductID().equals(MyApp.getInstance().getSlotList(0).get(j).getProduct().getProductID())) {
                remainingcount += MyApp.getInstance().getSlotList(0).get(j).getCount();
            }
        }

        holder.binding.productRemaining.setText(String.valueOf(remainingcount));
        holder.binding.textCount.setText(String.valueOf(count)+unit);
        holder.binding.buttonAddition.setOnClickListener(new addition1OnClickListener(context, holder.binding, position));
        holder.binding.buttonSubtraction.setOnClickListener(new subtraction1OnClickListener(context, holder.binding, position));

        logs.info("field:" + buyProduct.getField());

        try {
            SlotField slotField = SlotField.getSlotField(buyProduct.getField());
            logs.info("slotField:" + slotField.isCanAddPurchased());
            holder.binding.buttonAddition.setVisibility(slotField.isCanAddPurchased()?View.VISIBLE: View.GONE);
        } catch (LogsEmptyException e) {
            holder.binding.layoutEditCount.setVisibility(View.GONE);
        }

        int slot = buyProduct.getSlot();
        checkSlotHaveProduct(slot, count);
    }

    public void checkSlotHaveProduct(int slotnum, int slotcount) {
        logs.info("RecyclerDialogBuyListAdpter 111111111111111" + slotnum);
//            MyApp.getInstance().getDevXinYuanController().getReadBufferByNow(new DevCheckSlotByVMC(handlerMain));
        logs.info("RecyclerDialogBuyListAdpter 222222222222222"+slotcount);
        MyApp.getInstance().getDevXinYuanController().addSendBuffer(MyApp.getInstance().getDevXinYuanController().getDevXinYuan().checkSlotPre(slotnum,slotcount));
        logs.info("RecyclerDialogBuyListAdpter 333333333333333");
        MyApp.getInstance().getDevXinYuanController().addSendBuffer(MyApp.getInstance().getDevXinYuanController().getDevXinYuan().checkSlot(slotnum));
        logs.info("RecyclerDialogBuyListAdpter 444444444444444");
        MyApp.getInstance().getDevXinYuanController().getReadBufferByNow(new DevCheckSlotByVMC(handlerMain));
    }


    public class DevCheckSlotByVMC extends DevController.ReadBufferOnScheduler {
        public DevCheckSlotByVMC(HandlerMain handlerMain) {
            super(handlerMain);
        }

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

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

        @Override
        public void readBufferOnScheduler(DevController devController, HandlerMain handlerMain) {
            // 每次檢查前先重置門狀態旗標
            doorError = false;
            for (byte[] buffer: devController.getReadBufferByMax()) {
                if (buffer[0] == 0x02) {
                    getLogs().info("xxxxxxxxxxxxxxxxxxxxxxxxXinYuan Read:" + PortTools.showHex(buffer));
                    if (buffer[1] == 0x05) {
                        haveThings = true;
                        break;
                    }else if (buffer[1] == 0x06 || buffer[1] == 0x09) {
                        // 0x06：取貨口門沒關上
                        // 0x09：微波爐取貨口門關閉錯誤
                        getLogs().info("檢測到取貨口門未正常關閉，狀態碼=" + String.format("%02X", buffer[1]));
                        doorError = true;
                        break;
                    }
                }
            }

            if(haveThings){
                // 使用主執行緒顯示 AlertDialog
                new Handler(Looper.getMainLooper()).post(() -> {
                    AlertDialog dialog = new AlertDialog.Builder(context)
                            .setTitle(R.string.abnormal_reminder)
                            .setMessage(R.string.there_is_something_at_the_pickup_port)
                            .setCancelable(false)
                            .setPositiveButton(R.string.i_knew, (d, which) -> {
                                d.dismiss();
                                handlerMain.start(getClass().getSimpleName(), BuyDialog.Option.FORCE_CLOSE.getOption(), "force close");
                            })
                            .create();

                    dialog.show();

                    // 加入 10 秒後自動觸發點擊確定
                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                            handlerMain.start(getClass().getSimpleName(), BuyDialog.Option.FORCE_CLOSE.getOption(), "force close");
                        }
                    }, 10_000); // 10 秒（10000 毫秒）
                });
            }else if (doorError) {
                // 取貨口門未關閉，提示使用者並阻止後續購買流程
                doorError = false;
                handlerMain.start("RecycleFlowerBuyListAdpter", "取貨口門未正常關閉，請先確認門已關好");
                // 使用主執行緒顯示 AlertDialog
                new Handler(Looper.getMainLooper()).post(() -> {
                    AlertDialog dialog = new AlertDialog.Builder(context)
                            .setTitle(R.string.abnormal_reminder)
                            .setMessage("取貨口門未正常關閉，請先確認門已關好。")
                            .setCancelable(false)
                            .setPositiveButton(R.string.i_knew, (d, which) -> {
                                d.dismiss();
                                handlerMain.start(getClass().getSimpleName(), BuyDialog.Option.FORCE_CLOSE.getOption(), "force close");
                            })
                            .create();

                    dialog.show();

                    // 加入 10 秒後自動觸發點擊確定
                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                            handlerMain.start(getClass().getSimpleName(), BuyDialog.Option.FORCE_CLOSE.getOption(), "force close");
                        }
                    }, 10_000); // 10 秒（10000 毫秒）
                });
            }
        }
    }

    public class addition1OnClickListener implements View.OnClickListener {
        private Context context;
        private RecyclerDialogBuyListBinding binding;
        private int position;

        public addition1OnClickListener(Context context, RecyclerDialogBuyListBinding binding, int position) {
            this.context = context;
            this.binding = binding;
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            if (buyList.isEmpty()) return;

            BuyStructure buyProduct = buyList.get(position);

            int count = buyProduct.getCount();
            count++;
            buyList.get(position).setCount(count);

            String unit = "";

            try {
                SlotField slotField = SlotField.getSlotField(buyProduct.getField());
                switch (slotField) {
                    case VMC:
                        unit = buyProduct.isMarketingPlan() ? context.getString(R.string.group) : "";//組
                        break;
                    case ELECTRIC:
                        unit = buyProduct.isMarketingPlan() ? context.getString(R.string.group) : context.getString(R.string.hour);//組，小時
                        break;
                }
            } catch (LogsEmptyException e) {
                logs.warning(e);
            }

            binding.textCount.setText(String.valueOf(count)+unit);

            handlerMain.start(getClass().getSimpleName(), BuyDialog.Option.SET_PRICE.getOption(), "total price");
        }
    }

    public class subtraction1OnClickListener implements View.OnClickListener {
        private Context context;
        private RecyclerDialogBuyListBinding binding;
        private int position;
        public subtraction1OnClickListener(Context context, RecyclerDialogBuyListBinding binding, int position) {
            this.context = context;
            this.binding = binding;
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            if (buyList.isEmpty()) return;

            BuyStructure buyProduct = buyList.get(position);

            int count = buyProduct.getCount();
            count--;
            if (count <= 0) {
                buyList.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position, buyList.size() - position);

                handlerMain.start(getClass().getSimpleName(),context.getString(R.string.delete_a_record));//刪除一筆資料
            } else {
                buyList.get(position).setCount(count);

                String unit = "";

                try {
                    SlotField slotField = SlotField.getSlotField(buyProduct.getField());
                    switch (slotField) {
                        case VMC:
                            unit = buyProduct.isMarketingPlan() ? context.getString(R.string.group) : "";//組
                            break;
                        case ELECTRIC:
                            unit = buyProduct.isMarketingPlan() ? context.getString(R.string.group) : context.getString(R.string.hour);//組，小時
                            break;
                    }
                } catch (LogsEmptyException e) {
                    logs.warning(e);
                }

                binding.textCount.setText(String.valueOf(count) + unit);

                handlerMain.start(getClass().getSimpleName(), BuyDialog.Option.SET_PRICE.getOption(),"total price");
            }
        }
    }

    public class editCountOnEditorActionListener implements TextView.OnEditorActionListener{
        private ViewHolder holder;
        private int position;

        public editCountOnEditorActionListener(ViewHolder holder, int position) {
            this.holder = holder;
            this.position = position;
        }

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                int count = Integer.valueOf(v.getText().toString());
                buyList.get(position).setCount(count);
                notifyItemChanged(position);
                return true;
            }
            return false;
        }
    }

    public class textDeleteOnClickListener implements View.OnClickListener{
        private int position;

        public textDeleteOnClickListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            delProductData(position);
        }
    }
    @Override
    public int getItemCount() {
        return buyList.size();
    }

    public void addProductData(BuyStructure buyProduct) {
        buyList.add(buyProduct);
        notifyItemInserted(buyList.size() -1);
    }

    public void delProductData(int position) {
        buyList.remove(position);
        notifyItemRemoved(position);
    }
}
