package com.auto.clicker.autoclicker.ui.activity.main;

import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.view.accessibility.AccessibilityManager;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.auto.clicker.autoclicker.R;
import com.auto.clicker.autoclicker.databinding.ActivityMainBinding;
import com.auto.clicker.autoclicker.service.AutoClickService;
import com.auto.clicker.autoclicker.service.ForegroundService;
import com.auto.clicker.autoclicker.ui.activity.menu.MenuActivity;
import com.auto.clicker.autoclicker.ui.activity.setting.SettingActivity;
import com.auto.clicker.autoclicker.util.PrefUtils;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final String ACTION_FLOATING_STATE_CHANGED = "com.auto.clicker.autoclicker.FLOATING_WINDOW_STATE_CHANGED";

    private ActivityMainBinding binding;

    public static final int FLOATING_NONE = 0;
    public static final int FLOATING_SINGLE = 1;
    public static final int FLOATING_MULTI = 2;

    private Toast debounceToast;

    private ActivityResultLauncher<Intent> permissionLauncher;

    private long lastClickTime = 0;
    private static final long DEBOUNCE_INTERVAL = 500;

    private int isFloatingShown;
    private int selectedFloatingMode = FLOATING_SINGLE;

    private final BroadcastReceiver floatingReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            isFloatingShown = intent.getIntExtra("isShown", FLOATING_NONE);
            logDebug("接收到浮窗状态广播: isShown = " + isFloatingShown);
            
            if (isFloatingShown == FLOATING_NONE) {
            } else {
                selectedFloatingMode = isFloatingShown;
            }
            updateSelectionButtons();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        EdgeToEdge.enable(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initData();
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        logDebug("onResume: 检查权限和同步服务状态");
        checkPermissions();
        syncServiceState();
    }

    private void initData() {
        isFloatingShown = PrefUtils.getFloatingShown(this);
        if (isFloatingShown != FLOATING_NONE) {
            selectedFloatingMode = isFloatingShown;
        } else {
            selectedFloatingMode = FLOATING_SINGLE;
        }
        logDebug("initData: 初始化 isFloatingShown=" + isFloatingShown + ", selectedFloatingMode=" + selectedFloatingMode);

        updateSelectionButtons();

        LocalBroadcastManager.getInstance(this).registerReceiver(
                floatingReceiver, new IntentFilter(ACTION_FLOATING_STATE_CHANGED));

        permissionLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            logDebug("权限回调结果: " + result.getResultCode());
            binding.getRoot().postDelayed(() -> {
                checkPermissions();
                syncServiceState();
            }, 300);
        });

        setVideo(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.bolangblue));
    }

    private void initEvent() {
        binding.menu.setOnClickListener(v -> {
            Intent intent = new Intent(this, MenuActivity.class);
            startActivity(intent);
        });

        binding.question.setOnClickListener(v -> {
            Intent intent = new Intent(this, QuestionActivity.class);
            startActivity(intent);
        });

        binding.setting.setOnClickListener(v -> {
            Intent intent = new Intent(this, SettingActivity.class);
            startActivity(intent);
        });

        binding.animatedView.setOnClickListener(v -> onToggleFloatingWindowClicked());

        binding.single.setOnClickListener(v -> {
            if (isFloatingShown != FLOATING_NONE) {
                Toast.makeText(this, "请先关闭悬浮窗再切换模式", Toast.LENGTH_SHORT).show();
                return;
            }
            selectedFloatingMode = FLOATING_SINGLE;
            updateSelectionButtons();
            logDebug("选择单点模式. selectedFloatingMode=" + selectedFloatingMode);
        });

        binding.multi.setOnClickListener(v -> {
            if (isFloatingShown != FLOATING_NONE) {
                Toast.makeText(this, "请先关闭悬浮窗再切换模式", Toast.LENGTH_SHORT).show();
                return;
            }
            selectedFloatingMode = FLOATING_MULTI;
            updateSelectionButtons();
            logDebug("选择多点模式. selectedFloatingMode=" + selectedFloatingMode);
        });

    }

    private void checkPermissions() {
        boolean accessibilityGranted = isAccessibilityServiceEnabled();
        boolean overlayGranted = Settings.canDrawOverlays(this);
        boolean batteryOptimizationIgnored = isIgnoringBatteryOptimizations();

        logDebug("检查权限: 无障碍服务=" + accessibilityGranted + ", 悬浮窗=" + overlayGranted + ", 电池优化=" + batteryOptimizationIgnored);

        if (!accessibilityGranted) {
            logDebug("无障碍服务未启用，请求权限");
            showPermissionRequest(Settings.ACTION_ACCESSIBILITY_SETTINGS, "请启用无障碍服务以便应用正常工作", "无法打开无障碍设置");
            setStartButtonEnabled(false);
            
            return;
        }

        if (!overlayGranted) {
            logDebug("悬浮窗权限未授予，请求权限");
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
            showPermissionRequest(intent, "请授予悬浮窗权限，否则无法显示浮窗", "无法打开悬浮窗设置");
            setStartButtonEnabled(false);
            
            return;
        }

        if (!batteryOptimizationIgnored) {
            logDebug("电池优化未忽略，请求权限");
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            showPermissionRequest(intent, "请禁用电池优化，以确保应用在后台稳定运行", "无法打开电池优化设置");
            setStartButtonEnabled(false);
            
            return;
        }

        logDebug("所有权限均已授予");
        setStartButtonEnabled(true);
        
    }

    private void showPermissionRequest(String action, String toastMessage, String errorMessage) {
        try {
            Intent intent = new Intent(action);
            permissionLauncher.launch(intent);
            Toast.makeText(this, toastMessage, Toast.LENGTH_LONG).show();
            logDebug("尝试启动权限设置页面: " + action);
        } catch (Exception e) {
            Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
            logDebug("打开设置页面失败: " + errorMessage + ", 异常: " + e.getMessage());
        }
    }

    private void showPermissionRequest(Intent intent, String toastMessage, String errorMessage) {
        try {
            permissionLauncher.launch(intent);
            Toast.makeText(this, toastMessage, Toast.LENGTH_LONG).show();
            logDebug("尝试启动权限设置页面 (带URI): " + intent.getAction());
        } catch (Exception e) {
            Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
            logDebug("打开设置页面失败 (带URI): " + errorMessage + ", 异常: " + e.getMessage());
        }
    }

    private boolean isAccessibilityServiceEnabled() {
        AccessibilityManager am = (AccessibilityManager) getSystemService(Context.ACCESSIBILITY_SERVICE);
        if (am == null) return false;

        List<AccessibilityServiceInfo> enabledServices =
                am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK);

        String expectedId = new ComponentName(this, AutoClickService.class).flattenToShortString();

        for (AccessibilityServiceInfo enabledService : enabledServices) {
            if (enabledService.getId().equals(expectedId)) {
                return true;
            }
        }
        return false;
    }

    private boolean isIgnoringBatteryOptimizations() {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        boolean ignored = pm != null && pm.isIgnoringBatteryOptimizations(getPackageName());
        logDebug("是否忽略电池优化: " + ignored);
        return ignored;
    }

    private void syncServiceState() {
        int currentFloatingMode = getFloatingMode();
        logDebug("同步服务状态: 当前浮窗模式 = " + currentFloatingMode);
        isFloatingShown = currentFloatingMode;
        PrefUtils.setFloatingShown(this, isFloatingShown);
        
        updateSelectionButtons();
    }

    private int getFloatingMode() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        if (manager == null) {
            logDebug("ActivityManager 为空");
            return FLOATING_NONE;
        }

        List<ActivityManager.RunningServiceInfo> runningServices = manager.getRunningServices(Integer.MAX_VALUE);
        for (ActivityManager.RunningServiceInfo service : runningServices) {
            if (ForegroundService.class.getName().equals(service.service.getClassName())) {

                int mode = PrefUtils.getFloatingShown(this);
                logDebug("前台服务正在运行，PrefUtils 获取浮窗模式: " + mode);
                return mode;
            }
        }
        logDebug("前台服务未运行");
        return FLOATING_NONE;
    }

    public void onToggleFloatingWindowClicked() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastClickTime < DEBOUNCE_INTERVAL) {
            showDebounceToast();
            logDebug("点击过于频繁");
            return;
        }
        lastClickTime = currentTime;
        logDebug("点击启动/隐藏浮窗按钮. 当前 isFloatingShown=" + isFloatingShown + ", selectedFloatingMode=" + selectedFloatingMode);
        
        if (!isAccessibilityServiceEnabled() || !Settings.canDrawOverlays(this) || !isIgnoringBatteryOptimizations()) {
            Toast.makeText(this, "请授予所有必要权限", Toast.LENGTH_LONG).show();
            checkPermissions();
            logDebug("权限不足，无法启动浮窗，重新检查权限");
            return;
        }
        
        if (isFloatingShown != FLOATING_NONE && isFloatingShown != selectedFloatingMode) {
            Toast.makeText(this, "已显示其他悬浮窗，请先关闭", Toast.LENGTH_SHORT).show();
            logDebug("已显示其他模式的浮窗，请先关闭");
            return;
        }

        if (isFloatingShown == selectedFloatingMode) {

            logDebug("隐藏当前模式浮窗: " + selectedFloatingMode);
            stopService(new Intent(this, ForegroundService.class));

            if (AutoClickService.getInstance() != null) {
                AutoClickService.getInstance().stopClicking();
                logDebug("已停止 AutoClickService 点击");
            }
            isFloatingShown = FLOATING_NONE;
            logDebug("悬浮窗已经隐藏");
        } else {

            logDebug("启动浮窗: " + selectedFloatingMode);
            Intent serviceIntent = new Intent(this, ForegroundService.class);
            serviceIntent.putExtra("FLOATING_TYPE", selectedFloatingMode);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(serviceIntent);
            } else {
                startService(serviceIntent);
            }

            isFloatingShown = selectedFloatingMode;
            logDebug("悬浮窗已显示: " + selectedFloatingMode);
        }

        PrefUtils.setFloatingShown(this, isFloatingShown);
        broadcastFloatingState(isFloatingShown);
        updateSelectionButtons();

        if (isFloatingShown == FLOATING_NONE) {
            setVideo(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.bolangblue));
        } else {
            setVideo(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.bolangred));
        }
    }

    private void broadcastFloatingState(int isShown) {
        Intent intent = new Intent(ACTION_FLOATING_STATE_CHANGED);
        intent.putExtra("isShown", isShown);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        logDebug("发送浮窗状态广播: isShown = " + isShown);
    }

    private void updateSelectionButtons() {
        logDebug("更新选择按钮UI: selectedFloatingMode=" + selectedFloatingMode);

        if (selectedFloatingMode == FLOATING_SINGLE) {
            binding.single.setSelected(true);
            binding.multi.setSelected(false);

            binding.single.setBackgroundTintList(ContextCompat.getColorStateList(this, R.color.button_selected));
            binding.multi.setBackgroundTintList(ContextCompat.getColorStateList(this, R.color.button_unselected));
        } else if (selectedFloatingMode == FLOATING_MULTI) {
            binding.single.setSelected(false);
            binding.multi.setSelected(true);

            binding.single.setBackgroundTintList(ContextCompat.getColorStateList(this, R.color.button_unselected));
            binding.multi.setBackgroundTintList(ContextCompat.getColorStateList(this, R.color.button_selected));
        }

        binding.single.setEnabled(isFloatingShown == FLOATING_NONE);
        binding.multi.setEnabled(isFloatingShown == FLOATING_NONE);
    }

    private void setStartButtonEnabled(boolean enabled) {
        logDebug("设置启动按钮启用状态: " + enabled);
    }

    private void setVideo(Uri uri) {
        binding.animatedVideo.setVideoURI(uri);
        binding.animatedVideo.setOnPreparedListener(mp -> {
            mp.setLooping(true);
            mp.start();
        });
        binding.animatedVideo.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
        LocalBroadcastManager.getInstance(this).unregisterReceiver(floatingReceiver);
        if (debounceToast != null) {
            debounceToast.cancel();
        }
        logDebug("MainActivity onDestroy");
    }

    private void showDebounceToast() {
        if (debounceToast == null) {
            debounceToast = Toast.makeText(this, "点击太频繁", Toast.LENGTH_SHORT);
        } else {
            debounceToast.setText("点击太频繁");
        }
        debounceToast.show();
    }

    private void logDebug(String message) {
        Log.d(TAG, message);
    }
}