package com.unibuy.smartdevice;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.appcompat.app.AppCompatActivity;

import com.unibuy.smartdevice.exception.Logs;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.Tools;
import com.unibuy.smartdevice.ui.FontendActivity;

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

public abstract class DialogAbstract extends AlertDialog {
    private static final Map<Class<? extends DialogAbstract>, DialogAbstract> dialogInstances = new HashMap<>();
    private Context ctx;
    private Logs logs;
    private Tools tools;
    private HandlerMain handlerMain;
    private HandlerMain srcHandlerMain;


    public Context getCtx() {
        return ctx;
    }

    public Logs getLogs() {
        return logs;
    }

    public Tools getTools() {
        return tools;
    }

    public HandlerMain getHandlerMain() {
        return handlerMain;
    }

    public HandlerMain getSrcHandlerMain() {
        return srcHandlerMain;
    }

    protected abstract Context setCtx();
    protected abstract Class<? extends DialogAbstract> setCls();
    protected abstract HandlerMain setHandlerMain();

    public DialogAbstract(Context context, HandlerMain srcHandlerMain) {
        super(context);
        ctx = setCtx();
        this.logs = new Logs(setCls());
        this.tools = new Tools(getCtx(), logs);
        this.srcHandlerMain = srcHandlerMain;
        this.handlerMain = setHandlerMain();

        getLogs().info("open dialog:" + setCls().getSimpleName());
        getLogs().info("srcHandlerMain class:" + getSrcHandlerMain().getLogs().getClassName());
        getLogs().info("handlerMain class:" + getHandlerMain().getLogs().getClassName());

        setCanceledOnTouchOutside(false);
        setOnShowListener(dialogInterface -> {
            if (getWindow() != null) {
                getWindow().getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                );
            }
        });

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 設定對話框寬度為螢幕的 90%
        Window window = getWindow();
        if (window != null) {
            WindowManager.LayoutParams layoutParams = window.getAttributes();
//            layoutParams.width = (int) (getContext().getResources().getDisplayMetrics().widthPixels * 0.9);

            // 設定寬度為螢幕寬度
            layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;

            // 設定高度為包裹內容（可調整為 MATCH_PARENT）
            layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

            // 設定對話框貼齊底部
            layoutParams.gravity = Gravity.BOTTOM;

            window.setAttributes(layoutParams);
            getSrcHandlerMain().start(getClass().getSimpleName(), FontendActivity.Option.HIDDEN_MULTILANGUAGE_BUTTON.getOption(), "hidden button");
        }

        setCancelable(false);
        if (setCtx() instanceof Activity) {
            setOwnerActivity((Activity) setCtx());
        }

        MyApp.getInstance().setShowDialog(true);

        onCreate(setCtx());
    }

    public void changeDialog(Class<? extends DialogAbstract> cls) {
        try {
            // 檢查 getCtx() 和 getSrcHandlerMain() 返回有效值
            Context context = getCtx();
            HandlerMain handlerMain = getSrcHandlerMain();

            if (context == null || handlerMain == null) {
                getLogs().debug("Context or HandlerMain is null. Cannot proceed with dialog change.");
                return;
            }

            // 創建新對話框實例
            DialogAbstract newDialog = cls
                    .getConstructor(Context.class, HandlerMain.class)
                    .newInstance(context, handlerMain);

            // 顯示對話框
            if (!newDialog.isShowing()) {
                newDialog.show();
            }

            // 取消當前對話框
            this.cancel();

            getLogs().debug("dialog is change:" + cls.getSimpleName());
        } catch (Exception e) {
            getLogs().warning(e);
        }
    }


//    public void changeDialog(Class<? extends DialogAbstract> cls) {
//        try {
//            // 創建新對話框實例
//            DialogAbstract newDialog = cls
//                    .getConstructor(Context.class, HandlerMain.class)
//                    .newInstance(getCtx(), getSrcHandlerMain());
//
//            newDialog.show();
//            if (!newDialog.isShow()) {
//                newDialog.show();
//            }
//
//            // 取消當前對話框
//            super.cancel();
//        } catch (Exception e) {
//            getLogs().debug("Failed to change dialog: " + e.getMessage());
//        }
//    }

    @Override
    public void show() {
        Class<? extends DialogAbstract> cls = setCls();

        if (dialogInstances.containsKey(cls) && dialogInstances.get(cls).isShowing()) {
            getLogs().debug("dialog is open:" + cls.getSimpleName());
            getHandlerMain().start(cls.getSimpleName(), getLogs().getMessage());
            getLogs().clearMessage();
            return;
        }

        dialogInstances.put(cls, this);
        super.show();
        MyApp.getInstance().setShowDialog(true);
    }

    public boolean isShow() {
        Class<? extends DialogAbstract> cls = setCls();

        return dialogInstances.containsKey(cls);
    }

    @Override
    public void dismiss() {
        super.dismiss();
        // 在關閉對話框時，移除記錄並重置全域狀態
        dialogInstances.remove(setCls());
        if (dialogInstances.isEmpty()) {
            MyApp.getInstance().setShowDialog(false);
        }
    }

    protected abstract void onCreate(Context context);

    @Override
    public void cancel() {
        super.cancel();
        // MyApp.getInstance().setShowDialog(false); // 移至 dismiss 統一處理
        getSrcHandlerMain().start(getClass().getSimpleName(), FontendActivity.Option.SHOW_MULTILANGUAGE_BUTTON.getOption(), "show button");
    }
}
