package com.auto.clicker.autoclicker.util;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.auto.clicker.autoclicker.R;
import com.auto.clicker.autoclicker.room.entity.Solution;
import com.auto.clicker.autoclicker.room.repository.EventRepository;
import com.auto.clicker.autoclicker.ui.floating.SolutionAdapter;
import com.auto.clicker.autoclicker.view.FloatingViewManager;

import java.util.ArrayList;
import java.util.List;

public class FloatingTabDialogManager {

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

    private Button saveTab;
    private Button loadTab;
    private View savePage;
    private View loadPage;

    private FloatingViewManager floatingViewManager;

    private EditText inputName;
    private Button saveButton;
    private Button closeButton;

    private RecyclerView loadRecyclerview;
    private SolutionAdapter solutionsAdapter;
    private List<Solution> solutionList = new ArrayList<>();

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

    public void setFloatingViewManager(FloatingViewManager manager) {
        this.floatingViewManager = manager;
    }

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

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

        floatingDialogView = (LinearLayout) LayoutInflater.from(themedContext).inflate(R.layout.floating_tab_dialog, null);
        floatingDialogParams = createFloatingDialogParams(); // 创建悬浮窗参数

        saveTab = floatingDialogView.findViewById(R.id.tab_one_button);
        loadTab = floatingDialogView.findViewById(R.id.tab_two_button);
        savePage = floatingDialogView.findViewById(R.id.page_one_view);
        loadPage = floatingDialogView.findViewById(R.id.page_two_view);

        saveTab.setOnClickListener(v -> showPage(0));
        loadTab.setOnClickListener(v -> showPage(1));

        inputName = savePage.findViewById(R.id.script_name_input);
        saveButton = savePage.findViewById(R.id.save);
        closeButton = savePage.findViewById(R.id.close);

        saveButton.setOnClickListener(v -> {
            String solutionName = inputName.getText().toString().trim();

            if (floatingViewManager != null) {
                floatingViewManager.saveCurrentEventsAsSolution(solutionName, new EventRepository.RepositoryCallback<Long>() {
                    @Override
                    public void onComplete(Long solutionId) {
                        if (solutionId != -1) {
                            Toast.makeText(context, "方案 '" + solutionName + "' 保存成功！", Toast.LENGTH_SHORT).show();
                            removeFloatingTabDialog();
                        } else {
                            Toast.makeText(context, "保存方案失败。", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        Log.e(TAG, "保存方案失败: " + e.getMessage(), e);
                        Toast.makeText(context, "保存方案失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
                // ✅ 只在验证通过时才显示
                Toast.makeText(context, "正在保存方案...", Toast.LENGTH_SHORT).show();
            }
        });

        closeButton.setOnClickListener(v -> removeFloatingTabDialog());

        loadRecyclerview = loadPage.findViewById(R.id.script_list);
        loadRecyclerview.setLayoutManager(new LinearLayoutManager(context));

        solutionsAdapter = new SolutionAdapter(solutionList, solution -> {
            if (floatingViewManager != null) {
                floatingViewManager.loadSolution(solution.solutionId);
                Toast.makeText(context, "正在加载方案: " + solution.getSolutionName(), Toast.LENGTH_SHORT).show();
            } else {
                Log.e(TAG, "FloatingViewManager 未设置！无法加载方案。");
                Toast.makeText(context, "加载功能不可用，请联系开发者。", Toast.LENGTH_SHORT).show();
            }
            removeFloatingTabDialog();
        });
        loadRecyclerview.setAdapter(solutionsAdapter);

        showPage(0); // 默认显示保存页面

        loadSolutionsForList(); // 加载方案列表，以便切换到加载页面时可以直接显示

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

    private void showPage(int pageIndex) {
        if (savePage == null || loadPage == null) {
            Log.e(TAG, "页面视图未初始化！");
            return;
        }

        // 隐藏所有页面
        savePage.setVisibility(View.GONE);
        loadPage.setVisibility(View.GONE);

        // 重置Tab按钮颜色
        saveTab.setTextColor(context.getResources().getColor(android.R.color.darker_gray));
        loadTab.setTextColor(context.getResources().getColor(android.R.color.darker_gray));

        switch (pageIndex) {
            case 0: // 保存页面
                savePage.setVisibility(View.VISIBLE);
                saveTab.setTextColor(context.getResources().getColor(android.R.color.black));
                // 在显示保存页面时尝试显示键盘
                showKeyboard();
                break;
            case 1: // 加载页面
                loadPage.setVisibility(View.VISIBLE);
                loadTab.setTextColor(context.getResources().getColor(android.R.color.black));
                loadSolutionsForList();
                break;
        }
    }

    private void loadSolutionsForList() {
        if (floatingViewManager == null) {
            Log.e(TAG, "FloatingViewManager 未设置，无法加载方案列表。");
            // 确保UI操作在主线程
            new Handler(Looper.getMainLooper()).post(() ->
                    Toast.makeText(context, "加载方案列表功能不可用。", Toast.LENGTH_SHORT).show()
            );
            return;
        }
        floatingViewManager.getAllSolutions(new EventRepository.RepositoryCallback<List<Solution>>() {
            @Override
            public void onComplete(List<Solution> solutions) {
                // 将 UI 更新操作（包括更新适配器和显示Toast）切换到主线程
                new Handler(Looper.getMainLooper()).post(() -> {
                    solutionsAdapter.setSolutions(solutions);
                    if (solutions.isEmpty()) {
                        Toast.makeText(context, "没有可加载的方案。", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onError(Exception e) {
                // 将 UI 更新操作（显示Toast）切换到主线程
                new Handler(Looper.getMainLooper()).post(() -> {
                    Log.e(TAG, "加载方案列表失败: " + e.getMessage(), e);
                    Toast.makeText(context, "加载方案列表失败。", Toast.LENGTH_SHORT).show();
                });
            }
        });
    }

    public void removeFloatingTabDialog() {
        if (floatingDialogView != null) {
            try {
                windowManager.removeView(floatingDialogView);
                floatingDialogView = 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,
                PixelFormat.TRANSLUCENT
        );
        params.gravity = Gravity.CENTER;
        return params;
    }

    private void showKeyboard() {
        if (inputName != null) {
            inputName.requestFocus(); // 确保输入框获取焦点
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                // 尝试强制显示键盘
                imm.showSoftInput(inputName, InputMethodManager.SHOW_IMPLICIT);
            }
        }
    }
}