package com.auto.clicker.autoclicker.view;

import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.InputType;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.SwitchCompat;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.auto.clicker.autoclicker.R;
import com.auto.clicker.autoclicker.service.AutoClickService;

public class FloatingSettingDialogManager {

    private static final String TAG = "FloatingSettingDialogManager";
    private final Context context;
    private final WindowManager windowManager;
    private ConstraintLayout floatingDialogView;
    private WindowManager.LayoutParams floatingDialogParams;

    private static final int TYPE_INTERVAL = 0;
    private static final int TYPE_SWIPE_DURATION = 1;
    private static final int TYPE_REPEAT = 2;

    private LinearLayout intervalSelectorContainer;
    private LinearLayout unitSelectorContainer;
    private SwitchCompat repeatSwitch;
    private LinearLayout repeatInput;
    private LinearLayout repeatSelectorContainer;
    private EditText etIntervalValue;
    private TextView intervalSelectedUnit;
    private EditText etDurationValue;
    private TextView tvSelectedUnit;
    private EditText etRepeatValue;
    private TextView repeatSelectedUnit;
    private AppCompatButton saveButton;
    private AppCompatButton closeButton;

    private String currentIntervalUnit = "";
    private String currentSwipeDurationUnit = "";
    private String currentRepeatUnit = "";
    private String currentIntervalValue = "";
    private String currentDurationValue = "";
    private String currentRepeatValue = "";
    private boolean isRepeatSwitchChecked = false;

    public FloatingSettingDialogManager(Context context) {
        this.context = context;
        this.windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    }

    public void showFloatingTabDialog() {
        if (floatingDialogView != null) {
            removeFloatingTabDialog();
        }

        Context themedContext = new ContextThemeWrapper(context, R.style.Theme_AutoClicker);

        floatingDialogView = (ConstraintLayout) LayoutInflater.from(themedContext).inflate(R.layout.floating_setting_dialog, null);
        floatingDialogParams = createFloatingDialogParams();

        intervalSelectorContainer = floatingDialogView.findViewById(R.id.dialog_interval_selector_container);
        unitSelectorContainer = floatingDialogView.findViewById(R.id.dialog_unit_selector_container);
        repeatSwitch = floatingDialogView.findViewById(R.id.dialog_repeat_switch);
        repeatInput = floatingDialogView.findViewById(R.id.dialog_repeat_input);
        repeatSelectorContainer = floatingDialogView.findViewById(R.id.dialog_repeat_selector_container);
        etIntervalValue = floatingDialogView.findViewById(R.id.dialog_et_interval_value);
        intervalSelectedUnit = floatingDialogView.findViewById(R.id.dialog_interval_selected_unit);
        etDurationValue = floatingDialogView.findViewById(R.id.dialog_et_duration_value);
        tvSelectedUnit = floatingDialogView.findViewById(R.id.dialog_tv_selected_unit);
        etRepeatValue = floatingDialogView.findViewById(R.id.dialog_et_repeat_value);
        repeatSelectedUnit = floatingDialogView.findViewById(R.id.dialog_repeat_selected_unit);

        saveButton = floatingDialogView.findViewById(R.id.save);
        closeButton = floatingDialogView.findViewById(R.id.close);

        intervalSelectorContainer.setOnClickListener(v -> showUnitSelection(v, TYPE_INTERVAL));
        unitSelectorContainer.setOnClickListener(v -> showUnitSelection(v, TYPE_SWIPE_DURATION));

        setupRepeatMode();
        // --- 恢复UI状态 ---
        restoreUIState();

//        floatingDialogView.setOnTouchListener((v, event) -> {
//            if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
//                // 如果是外部点击事件，就关闭对话框
//                saveCurrentSettings();
//                removeFloatingTabDialog();
//                Log.d(TAG, "检测到外部点击，浮动标签页弹窗已关闭。");
//                return true; // 消费此事件
//            }
//            return false; // 其他事件不处理
//        });

        if (saveButton != null) {
            saveButton.setOnClickListener(v -> {
                saveCurrentSettings();
                applySettingsToService();
                removeFloatingTabDialog();
                showToastOnUi(context, "设置已保存！");
            });
        } else {
            Log.e(TAG, "Save button not found!");
        }

        if (closeButton != null) {
            closeButton.setOnClickListener(v -> {
                removeFloatingTabDialog();
                showToastOnUi(context, "设置已关闭，未保存更改。");
            });
        } else {
            Log.e(TAG, "Close button not found!");
        }

        try {
            windowManager.addView(floatingDialogView, floatingDialogParams);
            Log.d(TAG, "浮动标签页弹窗已显示");
        } catch (WindowManager.BadTokenException e) {
            Log.e(TAG, "无法添加浮动标签页弹窗，可能是权限问题或上下文无效", e);
            showToastOnUi(context, "显示弹窗失败，请检查权限。");
        } catch (SecurityException e) {
            Log.e(TAG, "需要悬浮窗权限才能显示浮动弹窗", e);
            showToastOnUi(context, "请授予悬浮窗权限以便显示。");
        }
    }

    public void removeFloatingTabDialog() {
        if (floatingDialogView != null) {
            try {
                windowManager.removeView(floatingDialogView);
                floatingDialogView = null;
                intervalSelectorContainer = null;
                unitSelectorContainer = null;
                repeatSwitch = null;
                repeatInput = null;
                repeatSelectorContainer = null;
                etIntervalValue = null;
                intervalSelectedUnit = null;
                etDurationValue = null;
                tvSelectedUnit = null;
                etRepeatValue = null;
                repeatSelectedUnit = null;
                saveButton = null;
                closeButton = null;

                Log.d(TAG, "浮动标签页弹窗已移除");
            } catch (IllegalArgumentException e) {
                Log.w(TAG, "尝试移除不存在的视图", e);
            }
        }
    }

    private WindowManager.LayoutParams createFloatingDialogParams() {
        int overlayType = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ?
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY :
                WindowManager.LayoutParams.TYPE_PHONE;

        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                overlayType,
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                        | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL // 允许将触摸事件传递到其下方窗口
                        | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, // 监听外部触摸事件
                PixelFormat.TRANSLUCENT
        );
        params.gravity = Gravity.CENTER;
        return params;
    }

    private void setupRepeatMode() {
        if (repeatSwitch == null || repeatInput == null || repeatSelectorContainer == null ||
                repeatSelectedUnit == null || etRepeatValue == null) {
            Log.e(TAG, "repeat mode UI components not found. Skipping setupRepeatMode.");
            return;
        }

        repeatSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            isRepeatSwitchChecked = isChecked; // 保存开关状态
            updateRepeatUI(isChecked);
        });

        repeatSelectorContainer.setOnClickListener(v -> showUnitSelection(v, TYPE_REPEAT));
    }

    private void updateRepeatUI(boolean isChecked) {
        if (isChecked) {
            repeatInput.setVisibility(View.VISIBLE);
            repeatSelectorContainer.setVisibility(View.VISIBLE);
            // 只有当单位是“无限次”时才禁用输入框
            if (currentRepeatUnit.equals(context.getString(R.string.infinitely_unit)) || repeatSelectedUnit.getText().toString().equals(context.getString(R.string.infinitely_unit))) {
                etRepeatValue.setText("");
                etRepeatValue.setEnabled(false);
                etRepeatValue.setInputType(InputType.TYPE_NULL);
                repeatSelectedUnit.setText(context.getString(R.string.infinitely_unit)); // 确保显示无限次
            } else {
                etRepeatValue.setEnabled(true);
                etRepeatValue.setInputType(InputType.TYPE_CLASS_NUMBER); // 默认设置为数字输入
                // 恢复之前的输入值和单位
                etRepeatValue.setText(currentRepeatValue);
                repeatSelectedUnit.setText(currentRepeatUnit.isEmpty() ? context.getString(R.string.cycle_unit) : currentRepeatUnit);
            }

        } else {
            repeatInput.setVisibility(View.GONE);
            repeatSelectorContainer.setVisibility(View.GONE);
        }
    }

    private void showUnitSelection(View anchorView, int type) {
        View popupView = LayoutInflater.from(context).inflate(R.layout.dialog_unit_selection, null);
        PopupWindow popupWindow = new PopupWindow(
                popupView,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true
        );

        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindow.setOutsideTouchable(true);

        TextView tvMs = popupView.findViewById(R.id.tv_unit_ms);
        TextView tvSec = popupView.findViewById(R.id.tv_unit_sec);
        TextView tvMin = popupView.findViewById(R.id.tv_unit_min);
        TextView tvInfinitely = popupView.findViewById(R.id.tv_unit_infinitely);
        TextView tvDuration = popupView.findViewById(R.id.tv_unit_duration);
        TextView tvCycle = popupView.findViewById(R.id.tv_unit_cycle);

        switch (type) {
            case TYPE_INTERVAL:
                tvMs.setVisibility(View.VISIBLE);
                tvSec.setVisibility(View.VISIBLE);
                tvMin.setVisibility(View.VISIBLE);
                tvInfinitely.setVisibility(View.GONE);
                tvDuration.setVisibility(View.GONE);
                tvCycle.setVisibility(View.GONE);
                break;
            case TYPE_SWIPE_DURATION:
                tvMs.setVisibility(View.VISIBLE);
                tvSec.setVisibility(View.VISIBLE);
                tvMin.setVisibility(View.GONE);
                tvInfinitely.setVisibility(View.GONE);
                tvDuration.setVisibility(View.GONE);
                tvCycle.setVisibility(View.GONE);
                break;
            case TYPE_REPEAT:
                tvMs.setVisibility(View.GONE);
                tvSec.setVisibility(View.GONE);
                tvMin.setVisibility(View.GONE);
                tvInfinitely.setVisibility(View.VISIBLE);
                tvDuration.setVisibility(View.VISIBLE);
                tvCycle.setVisibility(View.VISIBLE);
                Log.d(TAG, "TYPE_REPEAT: infinitely, duration, cycle visible.");
                break;
        }

        if (type == TYPE_INTERVAL || type == TYPE_SWIPE_DURATION) {
            tvMs.setOnClickListener(v -> {
                String unitText = context.getString(R.string.milliseconds_unit);
                if (type == TYPE_INTERVAL) {
                    intervalSelectedUnit.setText(unitText);
                    currentIntervalUnit = unitText;
                } else {
                    tvSelectedUnit.setText(unitText);
                    currentSwipeDurationUnit = unitText;
                }
                popupWindow.dismiss();
            });

            tvSec.setOnClickListener(v -> {
                String unitText = context.getString(R.string.seconds_unit);
                if (type == TYPE_INTERVAL) {
                    intervalSelectedUnit.setText(unitText);
                    currentIntervalUnit = unitText;
                } else {
                    tvSelectedUnit.setText(unitText);
                    currentSwipeDurationUnit = unitText;
                }
                popupWindow.dismiss();
            });

            if (type == TYPE_INTERVAL) {
                tvMin.setOnClickListener(v -> {
                    String unitText = context.getString(R.string.minutes_unit);
                    intervalSelectedUnit.setText(unitText);
                    currentIntervalUnit = unitText;
                    popupWindow.dismiss();
                });
            }
        }

        if (type == TYPE_REPEAT) {
            tvInfinitely.setOnClickListener(v -> {
                String unitText = context.getString(R.string.infinitely_unit);
                repeatSelectedUnit.setText(unitText);
                currentRepeatUnit = unitText;
                etRepeatValue.setText("");
                etRepeatValue.setEnabled(false);
                etRepeatValue.setInputType(InputType.TYPE_NULL);
                popupWindow.dismiss();
            });

            tvDuration.setOnClickListener(v -> {
                String unitText = context.getString(R.string.duration_unit);
                repeatSelectedUnit.setText(unitText);
                currentRepeatUnit = unitText;
                etRepeatValue.setText(""); // 清空以便用户输入新值
                etRepeatValue.setEnabled(true);
                etRepeatValue.setInputType(InputType.TYPE_CLASS_NUMBER);
                popupWindow.dismiss();
            });

            tvCycle.setOnClickListener(v -> {
                String unitText = context.getString(R.string.cycle_unit);
                repeatSelectedUnit.setText(unitText);
                currentRepeatUnit = unitText;
                etRepeatValue.setText("");
                etRepeatValue.setEnabled(true);
                etRepeatValue.setInputType(InputType.TYPE_CLASS_NUMBER);
                popupWindow.dismiss();
            });
        }

        if (type == TYPE_REPEAT) {
            popupWindow.showAsDropDown(anchorView, 0, -500);
        } else {
            popupWindow.showAsDropDown(anchorView);
        }
    }

    private void saveCurrentSettings() {
        currentIntervalValue = etIntervalValue.getText().toString();
        currentDurationValue = etDurationValue.getText().toString();
        currentRepeatValue = etRepeatValue.getText().toString();

        Log.d(TAG, "UI设置已保存到Manager: Interval=" + currentIntervalValue + " " + currentIntervalUnit +
                ", Duration=" + currentDurationValue + " " + currentSwipeDurationUnit +
                ", Repeat=" + currentRepeatValue + " " + currentRepeatUnit +
                ", RepeatSwitch=" + isRepeatSwitchChecked);
    }

    private void applySettingsToService() {
        AutoClickService service = AutoClickService.getInstance();
        if (service == null) {
            Log.e(TAG, "AutoClickService 实例为空，无法应用设置。");
            showToastOnUi(context, "自动点击服务未运行，无法应用设置。");
            return;
        }

        // 应用点击间隔
        long intervalValue = 0;
        if (!currentIntervalValue.isEmpty()) {
            try {
                intervalValue = Long.parseLong(currentIntervalValue);
                if (currentIntervalUnit.equals(context.getString(R.string.seconds_unit))) {
                    intervalValue *= 1000;
                } else if (currentIntervalUnit.equals(context.getString(R.string.minutes_unit))) {
                    intervalValue *= 60 * 1000;
                }
                service.setClickInterval(intervalValue);
                Log.d(TAG, "应用点击间隔到服务: " + intervalValue + "ms");
            } catch (NumberFormatException e) {
                Log.e(TAG, "点击间隔值解析错误: " + currentIntervalValue, e);
                showToastOnUi(context, "点击间隔值无效，请输入有效数字。");
            }
        } else {
            // 如果为空，设置一个默认值或不设置，这取决于你的业务逻辑
            // service.setClickInterval(默认值);
            Log.d(TAG, "点击间隔值为空，未应用到服务。");
        }

        int slideDurationValue = 0;
        if (!currentDurationValue.isEmpty()) {
            try {
                slideDurationValue = Integer.parseInt(currentDurationValue);
                if (currentSwipeDurationUnit.equals(context.getString(R.string.seconds_unit))) {
                    slideDurationValue *= 1000;
                }
                service.setSlideDuration(slideDurationValue);
                Log.d(TAG, "应用滑动时长到服务: " + slideDurationValue + "ms");
            } catch (NumberFormatException e) {
                Log.e(TAG, "滑动时长值解析错误: " + currentDurationValue, e);
                showToastOnUi(context, "滑动时长值无效，请输入有效数字。");
            }
        } else {
            // 如果为空，设置一个默认值或不设置
            // service.setSlideDuration(默认值);
            Log.d(TAG, "滑动时长值为空，未应用到服务。");
        }

        // 应用重复设置
        if (isRepeatSwitchChecked) {
            if (currentRepeatUnit.equals(context.getString(R.string.infinitely_unit))) {
                service.setLoopCount(0); // 无限循环
                Log.d(TAG, "应用重复模式: 无限次。");
            } else if (currentRepeatUnit.equals(context.getString(R.string.duration_unit))) {
                long repeatDurationMillis = 0;
                if (!currentRepeatValue.isEmpty()) {
                    try {
                        repeatDurationMillis = Long.parseLong(currentRepeatValue);
                        // 根据你的UI单位，这里可能需要进一步转换，例如用户输入的是秒
                        // repeatDurationMillis *= 1000L;
                        service.setLoopTime(repeatDurationMillis);
                        Log.d(TAG, "应用重复时长: " + repeatDurationMillis + "ms。");
                    } catch (NumberFormatException e) {
                        Log.e(TAG, "重复时长值解析错误: " + currentRepeatValue, e);
                        showToastOnUi(context, "重复时长值无效，请输入有效数字。");
                        service.setLoopTime(0); // 错误时，取消时间循环
                    }
                } else {
                    service.setLoopTime(0); // 如果值为空，取消时间循环
                    Log.d(TAG, "重复时长值为空，取消时间循环。");
                }
                service.setLoopCount(0); // 确保与时间循环互斥
            } else if (currentRepeatUnit.equals(context.getString(R.string.cycle_unit))) {
                int repeatCount = 0;
                if (!currentRepeatValue.isEmpty()) {
                    try {
                        repeatCount = Integer.parseInt(currentRepeatValue);
                        service.setLoopCount(repeatCount);
                        Log.d(TAG, "应用重复次数: " + repeatCount + "次。");
                    } catch (NumberFormatException e) {
                        Log.e(TAG, "重复次数值解析错误: " + currentRepeatValue, e);
                        showToastOnUi(context, "重复次数值无效，请输入有效数字。");
                        service.setLoopCount(1); // 错误时，设置为执行一次
                    }
                } else {
                    service.setLoopCount(1); // 如果值为空，设置为执行一次
                    Log.d(TAG, "重复次数值为空，设置为执行一次。");
                }
                service.setLoopTime(0); // 确保与次数循环互斥
            }
        } else {
            service.setLoopCount(1);
            service.setLoopTime(0);
            Log.d(TAG, "重复开关关闭，服务设置为执行一次。");
        }
    }

    private void restoreUIState() {
        // 恢复点击间隔
        if (!currentIntervalValue.isEmpty()) {
            etIntervalValue.setText(currentIntervalValue);
        }
        if (!currentIntervalUnit.isEmpty()) {
            intervalSelectedUnit.setText(currentIntervalUnit);
        } else {
            intervalSelectedUnit.setText(context.getString(R.string.milliseconds_unit)); // 默认单位
            currentIntervalUnit = context.getString(R.string.milliseconds_unit);
        }

        // 恢复滑动时长
        if (!currentDurationValue.isEmpty()) {
            etDurationValue.setText(currentDurationValue);
        }
        if (!currentSwipeDurationUnit.isEmpty()) {
            tvSelectedUnit.setText(currentSwipeDurationUnit);
        } else {
            tvSelectedUnit.setText(context.getString(R.string.milliseconds_unit)); // 默认单位
            currentSwipeDurationUnit = context.getString(R.string.milliseconds_unit);
        }

        // 恢复重复设置
        repeatSwitch.setChecked(isRepeatSwitchChecked);
        updateRepeatUI(isRepeatSwitchChecked); // 根据开关状态更新UI

        if (isRepeatSwitchChecked) {
            if (currentRepeatUnit.isEmpty()) {
                // 如果没有保存的单位，默认为无限次
                repeatSelectedUnit.setText(context.getString(R.string.infinitely_unit));
                currentRepeatUnit = context.getString(R.string.infinitely_unit);
                etRepeatValue.setText("");
                etRepeatValue.setEnabled(false);
                etRepeatValue.setInputType(InputType.TYPE_NULL);
            } else {
                repeatSelectedUnit.setText(currentRepeatUnit);
                if (currentRepeatUnit.equals(context.getString(R.string.infinitely_unit))) {
                    etRepeatValue.setText("");
                    etRepeatValue.setEnabled(false);
                    etRepeatValue.setInputType(InputType.TYPE_NULL);
                } else {
                    etRepeatValue.setText(currentRepeatValue);
                    etRepeatValue.setEnabled(true);
                    etRepeatValue.setInputType(InputType.TYPE_CLASS_NUMBER);
                }
            }
        }
    }

    public static void showToastOnUi(Context context, String msg) {
        new Handler(Looper.getMainLooper()).post(() ->
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
        );
    }

}