package com.unibuy.smartdevice.ui;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.unibuy.smartdevice.AppCompatActivityAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.R;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.structure.ProductStructure;
import com.unibuy.smartdevice.database.ProductsDao;
import com.unibuy.smartdevice.databinding.ActivityProductListBinding;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.HandlerMainSchedulerOnClick;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.ui.recycler.RecyclerProductListAdpter;
import com.unibuy.smartdevice.ui.tools.ImageGlide;
import com.unibuy.smartdevice.utils.LanguageHelper;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

public class ProductListActivity extends AppCompatActivityAbstract {
    public enum Option {
        TOAST(0),
        RESET_DATA(1),
        IMAGE_RELOAD(2),
        ;

        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 this;
    }

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

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getCtx(), getLogs()) {
            @Override
            protected void execute(Context context, int commandCode, String message) {
                // 處理 StarCloudAPI 的成功回傳
                if (commandCode == 200) {
                    // 立即刷新資料 (文字、價格等)，讓使用者先看到資料更新
                    runOnUiThread(() -> recyclerProductListAdpter.notifyDataSetChanged());
                    new ImagePreloadTask(ProductListActivity.this.getHandlerMain()).start();
                    return;
                }

                Option option = optionMap.get(commandCode);
                if (option != null) {
                    switch (option) {
                        case TOAST:
                            super.execute(context, commandCode, message);
                            runOnUiThread(() -> {
                                binding.progressLayout.setVisibility(View.GONE);
                                binding.buttonBack.setVisibility(View.VISIBLE);
                            });
                            break;
                        case RESET_DATA:
                            recyclerProductListAdpter.notifyDataSetChanged();
                            break;
                        case IMAGE_RELOAD:
                            new ImagePreloadTask(ProductListActivity.this.getHandlerMain()).start();
                            break;
                    }
                } else {
                    // 發生錯誤 (如非 200 代碼)，顯示訊息並恢復 UI
                    super.execute(context, commandCode, message);
                    runOnUiThread(() -> {
                        binding.progressLayout.setVisibility(View.GONE);
                        binding.buttonBack.setVisibility(View.VISIBLE);
                    });
                }
            }
        };
    }

    private ActivityProductListBinding binding;
    private RecyclerProductListAdpter recyclerProductListAdpter;
    private static WeakReference<ProductListActivity> instance;
    private static ProgressBar progressBar;
    private static TextView progressText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 讀取最後設定語言的設定
//        LanguageHelper.applySavedLanguage(this);
        this.binding = ActivityProductListBinding.inflate(getLayoutInflater());
        setContentView(this.binding.getRoot());

        instance = new WeakReference<>(this);
        progressBar = binding.progressBar;
        progressText = binding.progressText;

        this.recyclerProductListAdpter = new RecyclerProductListAdpter(this, MyApp.getInstance().getProductList());
        this.binding.recyclerProductList.setAdapter(recyclerProductListAdpter);
        this.binding.recyclerProductList.setLayoutManager(new LinearLayoutManager(this));

        binding.buttonBack.setOnClickListener(v -> finish());
        binding.buttonReload.setOnClickListener(v -> {
            new android.app.AlertDialog.Builder(ProductListActivity.this)
                .setTitle(getCtx().getString(R.string.sync_product))
                .setMessage(getCtx().getString(R.string.sync_product_warning))
                .setPositiveButton(getCtx().getString(R.string.sure), (dialog, which) -> {
                    com.unibuy.smartdevice.external.StarCloudAPI starCloudAPI = new com.unibuy.smartdevice.external.StarCloudAPI(getHandlerMain(), getHandlerMain());
                    try {
                        runOnUiThread(() -> {
                            binding.buttonBack.setVisibility(View.GONE);
                            binding.progressLayout.setVisibility(View.VISIBLE);
                            updateProgressUI(0, getCtx().getString(R.string.downloading_product_data));
                        });
                        ImageGlide.clearProductCache(ProductListActivity.this);
                        starCloudAPI.downloadProductInfo();
                    } catch (Exception e) {
                        getLogs().warning(e);
                        runOnUiThread(() -> {
                            binding.progressLayout.setVisibility(View.GONE);
                            binding.buttonBack.setVisibility(View.VISIBLE);
                        });
                    }
                })
                .setNegativeButton(getCtx().getString(R.string.cancel), null)
                .show();
        });

        if (MyApp.getInstance().getProductList().isEmpty()) {
            ProductsDao productsDao = new ProductsDao(this);
            for (ProductStructure product: productsDao.getAll()) {
                MyApp.getInstance().getProductList().add(product);
            }
            productsDao.close();
        }

        if (!MyApp.getInstance().getProductList().isEmpty()) {
            this.recyclerProductListAdpter.notifyItemInserted(MyApp.getInstance().getProductList().size() - 1);
        }
    }

    private class ImagePreloadTask extends HandlerMainSchedulerOnClick {
        public ImagePreloadTask(HandlerMain handlerMain) {
            super(handlerMain);
        }

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

        @Override
        protected void close(HandlerMain handlerMain) {
            handlerMain.start(getClass().getSimpleName(), Option.TOAST.getOption(), getCtx().getString(R.string.sync_completed));
            handlerMain.start(getClass().getSimpleName(), Option.RESET_DATA.getOption(), "reset data");
        }

        @Override
        protected void execute(HandlerMain handlerMain) {
            // 隱藏返回按鈕，顯示進度框 (UI thread)
            runOnUiThread(() -> {
                binding.buttonBack.setVisibility(View.GONE);
                binding.progressLayout.setVisibility(View.VISIBLE);
            });

            int adnum = MyApp.getInstance().getProductList().size();
            getLogs().info("ImagePreloadTask - 商品數量: " + adnum);
            if (adnum == 0) {
                getLogs().info("警告: 商品列表為空，無法預載圖片");
            }

            for (int i = 0; i < MyApp.getInstance().getProductList().size(); i++) {
                ProductStructure product = MyApp.getInstance().getProductList().get(i);
                if (product.getProductImg().isEmpty()) continue;

                try {
                    new ImageGlide(handlerMain.getContext()).preload(product.getProductImg());
                    // 下載完成後，立即刷新該項目的 UI (使 ImageGlide 重新判斷檔案存在，由淡變亮)
                    final int index = i;
                    runOnUiThread(() -> recyclerProductListAdpter.notifyItemChanged(index));
                } catch (LogsEmptyException e) {
                    getLogs().warning(e);
                }

                int persent = ((i + 1) * 100 / adnum);
                updateProgressUI(persent, getCtx().getString(R.string.syncing) + (i + 1) + "/" + adnum);
            }

            // 全部完成 → 隱藏進度框，顯示返回按鈕 (UI thread)
            runOnUiThread(() -> {
                binding.progressLayout.setVisibility(View.GONE);
                binding.buttonBack.setVisibility(View.VISIBLE);
            });
            close(handlerMain);
        }

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

        @Override
        public boolean onLongClick(View v) {
            return false;
        }

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

    public void updateProgressUI(int percent, String message) {
        ProductListActivity activity = instance.get();
        if (activity == null) return;

        activity.runOnUiThread(() -> {
            if (activity.progressBar != null) {
                activity.progressBar.setProgress(percent);
            }
            if (activity.progressText != null) {
                activity.progressText.setText(message + " (" + percent + "%)");
            }
        });
    }
}