package com.unibuy.smartdevice.ui.devs.vmc;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
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.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.unibuy.smartdevice.R;
import com.unibuy.smartdevice.databinding.RecyclerVmcSlotListBinding;
import com.unibuy.smartdevice.exception.Logs;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.structure.ProductStructure;
import com.unibuy.smartdevice.structure.SlotStructure;
import com.unibuy.smartdevice.tools.Tools;
import com.unibuy.smartdevice.ui.ProductSearchActivity;
import com.unibuy.smartdevice.ui.tools.ImageGlide;

import java.util.List;

public class RecyclerVmcSlotListAdpter extends RecyclerView.Adapter<RecyclerVmcSlotListAdpter.ViewHolder> {
    private Logs logs;
    private Context context;
    private Tools tools;
    private final ActivityResultLauncher<Intent> resultLauncher;
    private final List<SlotStructure> slotList;

    public RecyclerVmcSlotListAdpter(Context context, ActivityResultLauncher<Intent> resultLauncher, List<SlotStructure> slotList) {
        this.logs = new Logs(this.getClass());
        this.context = context;
        this.tools = new Tools(context, logs);
        this.resultLauncher = resultLauncher;
        this.slotList = slotList;
    }

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

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

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

        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        SlotStructure slot = slotList.get(position);
        holder.binding.textSlot.setText("貨道" + slot.getSlot());
        String productID = slot.getProduct().getProductID();
        if (!productID.isEmpty() && !productID.equals("?")) {
            holder.binding.textProductName.setText(slot.getProduct().getProductName());
        } else {
            holder.binding.textProductName.setText("選擇補貨商品");//點我選擇商品
        }
        holder.binding.textCount.setText(String.valueOf(slot.getCount()));
        holder.binding.editCount.setText(String.valueOf(slot.getCount()));
        // numberPassword 預設會遮罩輸入，關閉遮罩以顯示明碼數字
        holder.binding.editCount.setTransformationMethod(null);

        // 效期顯示＋編輯：永遠可點擊，補貨員現場輸入；空白顯示「設定效期」，已過期紅字標示
        String expiry = slot.getExpiryDate();
        holder.binding.textExpiry.setVisibility(View.VISIBLE);
        if (expiry.isEmpty()) {
            holder.binding.textExpiry.setText("設定效期");
            holder.binding.textExpiry.setTextColor(androidx.core.content.ContextCompat.getColor(context, R.color.black));
        } else if (slot.isExpired()) {
            holder.binding.textExpiry.setText("效期 " + expiry + "（已過期）");
            holder.binding.textExpiry.setTextColor(androidx.core.content.ContextCompat.getColor(context, R.color.warning));
        } else {
            holder.binding.textExpiry.setText("效期 " + expiry);
            holder.binding.textExpiry.setTextColor(androidx.core.content.ContextCompat.getColor(context, R.color.black));
        }
        holder.binding.textExpiry.setOnClickListener(v -> showExpiryPicker(position));

        if (slot.isLock()) {
            holder.binding.textLock.setChecked(false);
            holder.binding.textLockStatus.setText("停售中");
            holder.binding.textLockStatus.setTextColor(androidx.core.content.ContextCompat.getColor(context, R.color.warning));
            holder.binding.textLock.setThumbTintList(android.content.res.ColorStateList.valueOf(androidx.core.content.ContextCompat.getColor(context, R.color.warning)));
            holder.binding.textLock.setTrackTintList(android.content.res.ColorStateList.valueOf(androidx.core.graphics.ColorUtils.setAlphaComponent(androidx.core.content.ContextCompat.getColor(context, R.color.warning), 77)));
            holder.binding.viewProductMask.setVisibility(View.VISIBLE);
        } else {
            holder.binding.textLock.setChecked(true);
            holder.binding.textLockStatus.setText("販售中");
            holder.binding.textLockStatus.setTextColor(androidx.core.content.ContextCompat.getColor(context, R.color.success));
            holder.binding.textLock.setThumbTintList(android.content.res.ColorStateList.valueOf(androidx.core.content.ContextCompat.getColor(context, R.color.success)));
            holder.binding.textLock.setTrackTintList(android.content.res.ColorStateList.valueOf(androidx.core.graphics.ColorUtils.setAlphaComponent(androidx.core.content.ContextCompat.getColor(context, R.color.success), 77)));
            holder.binding.viewProductMask.setVisibility(View.GONE);
        }
        holder.binding.textLock.setOnClickListener(new textLockOnClickListener(position));

        String productImg = slot.getProduct().getProductImg();
        if (productImg != null && !productImg.isEmpty() && !productImg.equals("?")) {
            try {
                new ImageGlide(context).fileload(productImg, holder.binding.imageProduct);
            } catch (LogsEmptyException e) {
                holder.binding.imageProduct.setImageResource(R.drawable.slot_no_product);
            }
        } else {
            holder.binding.imageProduct.setImageResource(R.drawable.slot_no_product);
        }

        holder.binding.buttonCountMinus.setOnClickListener(v -> {
            int current = slot.getCount();
            if (current > 0) {
                slot.setCount(current - 1);
                notifyItemChanged(position);
            }
        });

        holder.binding.buttonCountPlus.setOnClickListener(v -> {
            int current = slot.getCount();
            slot.setCount(current + 1);
            notifyItemChanged(position);
        });

        holder.binding.imageProduct.setOnClickListener(new selectPositionOnClickListener(position));
        holder.binding.textProductName.setOnClickListener(null);
        holder.binding.textCount.setOnClickListener(new textCountOnClickListener(holder.binding, slot.getCount()));
        holder.binding.textDelete.setOnClickListener(new textDeleteOnClickListener(position));
        holder.binding.editCount.setOnEditorActionListener(new editCountOnEditorActionListener(holder.binding, position));
        holder.binding.editCount.setOnClickListener(new editCountOnClickListener(holder.binding, slot.getCount()));

        // 修正：移除不穩定的失去焦點邏輯，改用即時監聽 (TextWatcher)
        // 先移除舊的監聽器（如果有），避免 RecyclerView 重用 View 時產生衝突
        if (holder.binding.editCount.getTag() instanceof android.text.TextWatcher) {
            holder.binding.editCount.removeTextChangedListener((android.text.TextWatcher) holder.binding.editCount.getTag());
        }

        android.text.TextWatcher textWatcher = new android.text.TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(android.text.Editable s) {
                // 只有在輸入框有焦點（使用者正在打字）時才更新資料，避免 setText 觸發循環
                if (holder.binding.editCount.hasFocus()) {
                    int newCount = 0;
                    if (s.length() > 0) {
                        try {
                            newCount = Integer.parseInt(s.toString());
                        } catch (NumberFormatException ignored) {}
                    }
                    slotList.get(position).setCount(newCount);
                    holder.binding.textCount.setText(String.valueOf(newCount));
                }
            }
        };
        holder.binding.editCount.addTextChangedListener(textWatcher);
        holder.binding.editCount.setTag(textWatcher); // 將監聽器存入 Tag 以便下次重用時移除

        tools.setImmHideByFocusChange(holder.binding.editCount);
    }

    public class editCountOnClickListener implements View.OnClickListener {
        private RecyclerVmcSlotListBinding binding;
        private int count;

        public editCountOnClickListener(RecyclerVmcSlotListBinding binding, int count) {
            this.binding = binding;
            this.count = count;
        }

        @Override
        public void onClick(View v) {
            if (this.count == 0) {
                binding.editCount.setText("");
            }
        }
    }

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

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

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, ProductSearchActivity.class);
            intent.putExtra("position", position);
            resultLauncher.launch(intent);
        }
    }

    public class textCountOnClickListener implements ViewPager.OnClickListener{
        private RecyclerVmcSlotListBinding binding;
        private int count;

        public textCountOnClickListener(RecyclerVmcSlotListBinding binding, int count) {
            this.binding = binding;
            this.count = count;
        }

        @Override
        public void onClick(View v) {
            // 改用 INVISIBLE 而非 GONE，避免 buttonCountPlus 的 constraint 因 textCount 折疊
            // 導致 editCount 可用寬度被壓縮成 0（看不到輸入框、IME 無法接受輸入）
            binding.textCount.setVisibility(View.INVISIBLE);
            binding.editCount.setVisibility(View.VISIBLE);
            if (this.count == 0) {
                binding.editCount.setText("");
            }
            tools.setImmOpenByFocusChange(binding.editCount);
        }
    }

    public class editCountOnEditorActionListener implements TextView.OnEditorActionListener{
        private RecyclerVmcSlotListBinding binding;
        private int position;

        public editCountOnEditorActionListener(RecyclerVmcSlotListBinding binding, int position) {
            this.binding = binding;
            this.position = position;
        }

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                int count = 0;
                if (v.getText().length() > 0) {
                    count = Integer.valueOf(v.getText().toString());
                }
                slotList.get(position).setCount(count);
                binding.textCount.setText(String.valueOf(count));
                binding.editCount.setVisibility(View.GONE);
                binding.textCount.setVisibility(View.VISIBLE);
                notifyItemChanged(position);
                tools.hideSystemBars((Activity) context);
                return true;
            }
            return false;
        }
    }

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

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

        @Override
        public void onClick(View v) {
            setProductDataIsLock(position);
        }
    }

    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 slotList.size();
    }

    public void addProductData(SlotStructure productStructure) {
        slotList.add(productStructure);
        notifyItemInserted(slotList.size() -1);
    }

    public void setProductDataIsLock(int position) {
        slotList.get(position).setLock(slotList.get(position).isLock()?false:true);
        notifyItemChanged(position);
    }

    /**
     * 開效期日期選擇器供補貨員現場輸入；提供「清除效期」表示無效期管控。
     * 僅改記憶體值（rev 由 VmcSlotListActivity 存檔時與 baseline 比對後統一遞增）。
     */
    private void showExpiryPicker(int position) {
        final SlotStructure slot = slotList.get(position);
        java.util.Calendar cal = java.util.Calendar.getInstance();
        String cur = slot.getExpiryDate();
        try {
            if (cur != null && cur.length() >= 10) {
                cal.set(Integer.parseInt(cur.substring(0, 4)),
                        Integer.parseInt(cur.substring(5, 7)) - 1,
                        Integer.parseInt(cur.substring(8, 10)));
            }
        } catch (Exception ignored) {}

        android.app.DatePickerDialog dialog = new android.app.DatePickerDialog(
                context,
                (view, year, month, day) -> {
                    String date = String.format(java.util.Locale.US, "%04d-%02d-%02d", year, month + 1, day);
                    slot.setExpiryDate(date);
                    notifyItemChanged(position);
                },
                cal.get(java.util.Calendar.YEAR),
                cal.get(java.util.Calendar.MONTH),
                cal.get(java.util.Calendar.DAY_OF_MONTH));
        dialog.setButton(android.app.DatePickerDialog.BUTTON_NEUTRAL, "清除效期", (d, w) -> {
            slot.setExpiryDate("");
            notifyItemChanged(position);
        });
        dialog.show();
    }

    public void delProductData(int position) {
        slotList.get(position).setProduct(new ProductStructure("?", "", "", 0, 0, 0, 0, "", "","",""));
        slotList.get(position).setCount(0);
        slotList.get(position).setLock(false);
        notifyItemChanged(position);
    }
}
