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

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.unibuy.smartdevice.AppCompatActivityAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.R;
import com.unibuy.smartdevice.databinding.ActivityVmcSlotListBinding;
import com.unibuy.smartdevice.devices.SlotField;
import com.unibuy.smartdevice.exception.ErrorCode;
import com.unibuy.smartdevice.exception.LogsParseException;
import com.unibuy.smartdevice.exception.LogsSettingEmptyException;
import com.unibuy.smartdevice.external.HttpAPI;
import com.unibuy.smartdevice.external.StarCloudAPI;
import com.unibuy.smartdevice.structure.ProductStructure;
import com.unibuy.smartdevice.structure.ReportSlotListStructure;
import com.unibuy.smartdevice.structure.SlotStructure;
import com.unibuy.smartdevice.database.SlotsDao;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.ui.devs.electric.ElectricSlotListActivity;

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

public class VmcSlotListActivity extends AppCompatActivityAbstract {
    private ActivityVmcSlotListBinding binding;
    private ActivityResultLauncher<Intent> resultLauncher;
    private RecyclerVmcSlotListAdpter recyclerVmcSlotListAdpter;
    private HttpAPI httpAPI;
    private StarCloudAPI starCloudAPI;

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

    @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) {
                // 無論成功或失敗，都隱藏進度條並恢復按鈕
                if (binding != null && binding.progressLayout != null) {
                    binding.progressLayout.setVisibility(View.GONE);
                    binding.buttonBack.setEnabled(true);
                    binding.buttonSave.setEnabled(true);
                }
                super.execute(context, commandCode, message);
                // 上傳完成（同步成功）後自動返回前一頁
                if (commandCode == 200) {
                    finish();
                } else {
                    // 同步失敗，彈出確認對話框，提供「重試」與「直接返回」的後路，防止因返回鍵隱藏而卡死
                    if (context instanceof android.app.Activity) {
                        android.app.Activity activity = (android.app.Activity) context;
                        if (!activity.isFinishing() && !activity.isDestroyed()) {
                            new android.app.AlertDialog.Builder(context)
                                    .setTitle("同步失敗")
                                    .setMessage("上傳貨道資料至後台失敗，請檢查網路連線。\n您要重新嘗試同步，或是直接返回上一頁？")
                                    .setCancelable(false) // 避免誤觸外部關閉對話框
                                    .setPositiveButton("重新嘗試", (dialog, which) -> {
                                        // 重新顯示進度條並鎖定按鈕，再次執行同步
                                        if (binding != null && binding.progressLayout != null) {
                                            binding.progressLayout.setVisibility(View.VISIBLE);
                                            binding.buttonBack.setEnabled(false);
                                            binding.buttonSave.setEnabled(false);
                                        }
                                        updateSlotListNum();
                                    })
                                    .setNegativeButton("直接返回", (dialog, which) -> {
                                        // 直接關閉頁面返回
                                        finish();
                                    })
                                    .show();
                        }
                    }
                }
            }
        };
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityVmcSlotListBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        httpAPI = new HttpAPI(getHandlerMain());
        starCloudAPI = new StarCloudAPI(getHandlerMain(), getHandlerMain());
        resultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult o) {
                    if (o.getResultCode() == RESULT_OK && o.getData() != null) {
                        int position = o.getData().getIntExtra("position", 0);
                        int slot = MyApp.getInstance().getSlotList(SlotField.VMC.getField()).get(position).getSlot();
                        String productId = o.getData().getStringExtra("product_id");
                        getLogs().info("接收到回傳值:" + position + "," + slot + "," + productId);
                        for(ProductStructure product: MyApp.getInstance().getProductList()) {
                            if (product.getProductID().equals(productId)) {
                                MyApp.getInstance().getSlotList(SlotField.VMC.getField()).set(position, new SlotStructure(SlotField.VMC.getField(), slot, product, 0));
                                break;
                            }
                        }
                        recyclerVmcSlotListAdpter.notifyItemChanged(position);
                    }
                }
            }
        );

//        MyApplication.getInstance().initialSlotData();

        recyclerVmcSlotListAdpter = new RecyclerVmcSlotListAdpter(this, resultLauncher, MyApp.getInstance().getSlotList(SlotField.VMC.getField()));
        binding.recyclerSlotList.setAdapter(recyclerVmcSlotListAdpter);
        binding.recyclerSlotList.setLayoutManager(new LinearLayoutManager(this));

//        dataShow();

        binding.buttonBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 如果有進度條在跑，不允許直接返回
                if (binding.progressLayout.getVisibility() == View.VISIBLE) {
                    return;
                }
                finish();
            }
        });

        binding.buttonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 強制清除目前焦點，確保輸入框 (editCount) 觸發失去焦點儲存事件
                View currentFocus = getCurrentFocus();
                if (currentFocus != null) {
                    currentFocus.clearFocus();
                }
                String validationError = validateMaterialCodeConsistency();
                if (!validationError.isEmpty()) {
                    getHandlerMain().start(getClass().getSimpleName(), "@" + validationError);
                    return;
                }

                // 1. 本地儲存
                saveData();
                
                // 2. 顯示進度條並開始雲端同步
                binding.progressLayout.setVisibility(View.VISIBLE);
                binding.buttonBack.setEnabled(false);
                binding.buttonSave.setEnabled(false);
                
                updateSlotListNum();
            }
        });

        binding.buttonReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearData();
                saveData();
                dataShow();
            }
        });

        //一鍵補貨全部貨道的貨道上限數
        binding.buttonoOneClickReplenishment.setOnClickListener(v -> {
            for (int i = 0; i < MyApp.getInstance().getSlotList(SlotField.VMC.getField()).size(); i++) {
                SlotStructure slot = MyApp.getInstance().getSlotList(SlotField.VMC.getField()).get(i);
                ProductStructure product = slot.getProduct();

                // 判斷有沒有設定商品
                if (product != null && !product.getProductID().isEmpty() && !product.getProductID().equals("?")) {
                    int upperLimit = product.getSlotUpperLimit();
                    slot.setCount(upperLimit); // 設定數量 = 貨道上限
                    getLogs().info("補貨完成：貨道 " + slot.getSlot() + " → " + upperLimit);
                    recyclerVmcSlotListAdpter.notifyItemChanged(i); // 更新 UI
                }
            }
        });


//        binding.buttonGotoElectricSlotList.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                saveData();
//                gotoElectricAcitvity();
//            }
//        });
//
//        if (MyApp.getInstance().getDevSet().isElectic()) {
//            binding.buttonGotoElectricSlotList.setVisibility(View.VISIBLE);
//        } else {
//            binding.buttonGotoElectricSlotList.setVisibility(View.GONE);
//        }
    }

    public void gotoElectricAcitvity() {
        startActivity(new Intent(this, ElectricSlotListActivity.class));
        finish();
    }

    private void saveData() {
        SlotsDao slotsDao = new SlotsDao(this);
        slotsDao.deleteAll();
        slotsDao.insertAll(MyApp.getInstance().getSlotMap());
        slotsDao.close();
        getLogs().info("save count:"+ MyApp.getInstance().getSlotList(SlotField.VMC.getField()).size());
    }

    public void clearData() {
        SlotsDao slotsDao = new SlotsDao(this);
        slotsDao.deleteAll();
        slotsDao.close();
        int slotListSize = MyApp.getInstance().getSlotList(SlotField.VMC.getField()).size();
        MyApp.getInstance().getSlotList(SlotField.VMC.getField()).clear();
        if (slotListSize > 0) {
            recyclerVmcSlotListAdpter.notifyItemRangeRemoved(0, slotListSize);
        }
        if (MyApp.getInstance().getSlotList(SlotField.VMC.getField()).isEmpty()) {
            for (int i = 1; i <= 60; i++) {
                MyApp.getInstance().getSlotList(SlotField.VMC.getField()).add(new SlotStructure(SlotField.VMC.getField(), i,
                        new ProductStructure("?", "", "", 0, 0, 0, 0, "", "","",""),
                        0));
            }
            getLogs().info(SlotField.VMC.getField() + " count:"+ MyApp.getInstance().getSlotList(SlotField.VMC.getField()).size());
        }
    }

    private void testData() {
        for(int i=1;i<=60;i++) {
            MyApp.getInstance().getSlotList(SlotField.VMC.getField()).add(new SlotStructure(SlotField.VMC.getField(), i,
                new ProductStructure(
                "1000",
                "gg1.png",
                "測試小精靈"+i,
                100+1,
                100+2,
                100+3,
                8,
                        "",
                        "",
                        "",
                        ""
                ), 3));
        }
    }

    public void dataShow() {
        getLogs().info("recycler data count:"+this.recyclerVmcSlotListAdpter.getItemCount());
        recyclerVmcSlotListAdpter.notifyItemInserted(MyApp.getInstance().getSlotList(SlotField.VMC.getField()).size() -1);
    }

    public void updateSlotListNum(){
        ReportSlotListStructure data = MyApp.getInstance().getReportSlotListStructure();
        data.setAccount(MyApp.getInstance().getSuAccess());
        // 如果 Intent 沒傳 vmcType，預設給 "U4"
        String vmcType = getIntent().getStringExtra("vmctype");
        if (vmcType == null || vmcType.isEmpty()) vmcType = "U4";
        data.setVmctype(vmcType);

        try {
            this.starCloudAPI.reportSlotList(data);
        } catch (Exception e) {
            getLogs().error(ErrorCode.NETWORK_UNKNOWN_ERROR, "同步啟動失敗: " + e.getMessage());
        }
    }

    private String validateMaterialCodeConsistency() {
        for (SlotStructure slot : MyApp.getInstance().getSlotList(SlotField.VMC.getField())) {
            if (slot == null || slot.getProduct() == null) continue;
            ProductStructure product = slot.getProduct();
            String productId = product.getProductID() == null ? "" : product.getProductID().trim();
            if (productId.isEmpty() || "?".equals(productId)) continue;
            String materialCode = product.getMaterialCode() == null ? "" : product.getMaterialCode().trim();
            if (materialCode.isEmpty()) {
                return getString(R.string.vmc_material_code_empty, slot.getSlot(), productId);
            }
        }
        return "";
    }
}
