package com.auto.clicker.autoclicker.util;

import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.auto.clicker.autoclicker.R;
import com.auto.clicker.autoclicker.data.PointEvent;
import com.auto.clicker.autoclicker.data.SlideEvent;
import com.auto.clicker.autoclicker.view.ConnectingLineView;

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

public class EventViewBinder {

    // 存储每个视图及其对应的 OnTouchListener 实例，用于启用/禁用拖动
    private static final Map<View, View.OnTouchListener> activeDragListeners = new HashMap<>();

    public interface OnPositionChangedCallback {
        void onPositionChanged(int x, int y);
    }

    // --- bindPoint 方法 ---
    public static void bindPoint(Context context, WindowManager windowManager,
                                 PointEvent pointEvent, int touchPointSize,
                                 int screenWidth, int screenHeight,
                                 OnPositionChangedCallback callback, int order, float initialTextSize) {

        TextView pointView = createTouchPointView(context, String.valueOf(order));
        Log.d("bind", "id: " + order);
        WindowManager.LayoutParams params = createTouchPointParams(context, touchPointSize);

        params.x = pointEvent.getX();
        params.y = pointEvent.getY();

        pointEvent.setView(pointView);
        pointEvent.setLayoutParams(params);

        pointView.setTextSize(TypedValue.COMPLEX_UNIT_SP, initialTextSize);

        // 创建并保存 OnTouchListener
        View.OnTouchListener touchListener = createTouchListener(
                pointView, params, windowManager, screenWidth, screenHeight,
                (x, y) -> {
                    pointEvent.setX(x);
                    pointEvent.setY(y);
                    if (callback != null) callback.onPositionChanged(x, y);
                });

        pointView.setOnTouchListener(touchListener);
        activeDragListeners.put(pointView, touchListener); // 保存监听器到 Map

        windowManager.addView(pointView, params);
    }

    // --- bindSlide 方法 ---
    public static void bindSlide(Context context, WindowManager windowManager,
                                 SlideEvent slideEvent, int touchPointSize,
                                 int screenWidth, int screenHeight,
                                 OnPositionChangedCallback callback, int order, float initialTextSize) {

        PointEvent start = slideEvent.getStartPoint();
        PointEvent end = slideEvent.getEndPoint();

        TextView startView = createTouchPointView(context, String.valueOf(order));
        TextView endView = createTouchPointView(context, String.valueOf(order));
        WindowManager.LayoutParams startParams = createTouchPointParams(context, touchPointSize);
        WindowManager.LayoutParams endParams = createTouchPointParams(context, touchPointSize);

        startParams.x = start.getX();
        startParams.y = start.getY();
        endParams.x = end.getX();
        endParams.y = end.getY();

        start.setView(startView);
        start.setLayoutParams(startParams);
        end.setView(endView);
        end.setLayoutParams(endParams);

        startView.setTextSize(TypedValue.COMPLEX_UNIT_SP, initialTextSize);
        endView.setTextSize(TypedValue.COMPLEX_UNIT_SP, initialTextSize);

        ConnectingLineView lineView = new ConnectingLineView(context);
        WindowManager.LayoutParams lineParams = createLineViewParams(context);

        slideEvent.setLineView(lineView);
        slideEvent.setLineParams(lineParams);

        // 拖动起点 - 创建并保存监听器
        View.OnTouchListener startTouchListener = createTouchListener(
                startView, startParams, windowManager, screenWidth, screenHeight,
                (x, y) -> {
                    start.setX(x);
                    start.setY(y);
                    updateLinePosition(slideEvent, touchPointSize);
                    if (callback != null) callback.onPositionChanged(x, y);
                });
        startView.setOnTouchListener(startTouchListener);
        activeDragListeners.put(startView, startTouchListener); // 保存监听器

        // 拖动终点 - 创建并保存监听器
        View.OnTouchListener endTouchListener = createTouchListener(
                endView, endParams, windowManager, screenWidth, screenHeight,
                (x, y) -> {
                    end.setX(x);
                    end.setY(y);
                    updateLinePosition(slideEvent, touchPointSize);
                    if (callback != null) callback.onPositionChanged(x, y);
                });
        endView.setOnTouchListener(endTouchListener);
        activeDragListeners.put(endView, endTouchListener); // 保存监听器

        windowManager.addView(lineView, lineParams);
        windowManager.addView(startView, startParams);
        windowManager.addView(endView, endParams);

        updateLinePosition(slideEvent, touchPointSize);
    }

    // --- 从 DraggableHelper 移动过来的 OnTouchListener 创建逻辑 ---
    // 这个方法创建并返回一个 View.OnTouchListener 实例
    private static View.OnTouchListener createTouchListener(
            View view, WindowManager.LayoutParams params, WindowManager windowManager,
            int screenWidth, int screenHeight, DraggableHelper.DragCallback callback) { // 仍然使用 DraggableHelper.DragCallback 接口
        return new View.OnTouchListener() {
            private float lastX, lastY;
            private float paramX, paramY;
            private boolean isDragging = false; // 标记是否正在拖动

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        lastX = event.getRawX();
                        lastY = event.getRawY();
                        paramX = params.x;
                        paramY = params.y;
                        isDragging = false; // 重置拖动状态
                        return true;

                    case MotionEvent.ACTION_MOVE:
                        isDragging = true; // 正在拖动
                        float dx = event.getRawX() - lastX;
                        float dy = event.getRawY() - lastY;

                        int newX = (int) (paramX + dx);
                        int newY = (int) (paramY + dy);

                        newX = Math.max(0, Math.min(newX, screenWidth - view.getWidth()));
                        newY = Math.max(0, Math.min(newY, screenHeight - view.getHeight()));

                        params.x = newX;
                        params.y = newY;

                        windowManager.updateViewLayout(view, params);

                        if (callback != null) {
                            callback.onPositionChanged(newX, newY);
                        }
                        return true;

                    case MotionEvent.ACTION_UP:
                        if (!isDragging) { // 如果没有拖动，才视为点击
                            v.performClick();
                        }
                        return true;
                }
                return false;
            }
        };
    }

    // --- 新增方法：统一控制所有触摸点的拖动状态 ---
    public static void setAllTouchPointsDraggable(boolean draggable) {
        for (Map.Entry<View, View.OnTouchListener> entry : activeDragListeners.entrySet()) {
            View view = entry.getKey();
            View.OnTouchListener listener = entry.getValue();
            if (draggable) {
                // 启用拖动：重新设置保存的监听器
                view.setOnTouchListener(listener);
            } else {
                // 禁用拖动：将监听器设置为 null，阻止触摸事件
                view.setOnTouchListener(null);
            }
        }
    }

    // --- 新增方法：移除不再需要的视图及其监听器 ---
    public static void removeBoundView(WindowManager windowManager, View view) {
        if (view != null) {
            try {
                windowManager.removeView(view);
                activeDragListeners.remove(view); // 从 Map 中移除
                Log.d("EventViewBinder", "移除视图并清理监听器: " + view.getTag());
            } catch (IllegalArgumentException e) {
                Log.e("EventViewBinder", "尝试移除不存在的视图: " + e.getMessage());
            }
        }
    }

    // --- 辅助方法 (保持不变) ---
    public static TextView createTouchPointView(Context context, String label) {
        TextView touchPointView = new TextView(context);
        touchPointView.setBackgroundResource(R.drawable.ring_has_bg);
        touchPointView.setGravity(Gravity.CENTER);
        touchPointView.setText(label);
        touchPointView.setTextColor(Color.WHITE);
        touchPointView.setTag(label); // 添加一个Tag，方便日志识别
        return touchPointView;
    }

    private static WindowManager.LayoutParams createTouchPointParams(Context context, int size) {
        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(
                size, size,
                overlayType,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                        WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                PixelFormat.TRANSLUCENT
        );
        params.gravity = Gravity.TOP | Gravity.START;
        return params;
    }

    private static WindowManager.LayoutParams createLineViewParams(Context context) {
        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.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                overlayType,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                        WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                        WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, // 线条通常不可触摸
                PixelFormat.TRANSLUCENT
        );
        params.gravity = Gravity.TOP | Gravity.START;
        params.x = 0;
        params.y = 0;
        return params;
    }

    public static void updateLinePosition(SlideEvent slideEvent, int touchPointSize) {
        PointEvent start = slideEvent.getStartPoint();
        PointEvent end = slideEvent.getEndPoint();
        ConnectingLineView lineView = slideEvent.getLineView();

        if (lineView == null) return;

        float startCenterX = start.getX() + (float) touchPointSize / 2;
        float startCenterY = start.getY() + (float) touchPointSize / 2;
        float endCenterX = end.getX() + (float) touchPointSize / 2;
        float endCenterY = end.getY() + (float) touchPointSize / 2;

        lineView.setPoints(startCenterX, startCenterY, endCenterX, endCenterY);
    }
}