package com.miraclegarden.smsmessage.Activity;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.miraclegarden.library.app.MiracleGardenActivity;
import com.miraclegarden.smsmessage.databinding.ActivityMainBinding;
import com.miraclegarden.smsmessage.network.TokenManager;
import com.miraclegarden.smsmessage.util.OEMBackgroundHelper;

public class MainActivity extends MiracleGardenActivity<ActivityMainBinding> {

    private TokenManager tokenManager;

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

        tokenManager = TokenManager.getInstance(this);

        // 调试用：暂时跳过登录
//        if (!tokenManager.isLoggedIn()) {
//            startActivity(new Intent(this, LoginActivity.class));
//            finish();
//            return;
//        }

        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 调试用：暂时跳过登录
//        if (!tokenManager.isLoggedIn()) {
//            startActivity(new Intent(this, LoginActivity.class));
//            finish();
//            return;
//        }
        updatePermissionStatus();
    }

    private void initView() {
        String username = tokenManager.getUsername();
        if (username != null) {
            binding.tvUsername.setText(username);
        }

        binding.tvDeviceBrand.setText("检测到设备: " + OEMBackgroundHelper.getManufacturer());

        binding.btnLogout.setOnClickListener(v -> logout());

        binding.btnStartMonitoring.setOnClickListener(v -> {
            startActivity(new Intent(this, NotificationActivity.class));
        });

        binding.btnBankManage.setOnClickListener(v -> {
            startActivity(new Intent(this, BankListActivity.class));
        });

        binding.btnMmpClaim.setOnClickListener(v -> {
            startActivity(new Intent(this, MmpClaimActivity.class));
        });

        binding.permissionNotificationAccess.setOnClickListener(v -> {
            startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));
        });

        binding.permissionPostNotifications.setOnClickListener(v -> {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
                        != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.POST_NOTIFICATIONS}, 100);
                }
            }
        });

        binding.permissionBattery.setOnClickListener(v -> {
            requestBatteryOptimization();
        });

        binding.btnAutostart.setOnClickListener(v -> {
            OEMBackgroundHelper.openAutoStartSettings(this);
        });

        binding.btnBatteryOptimization.setOnClickListener(v -> {
            OEMBackgroundHelper.requestBatteryOptimizationExemption(this);
        });
    }

    private void logout() {
        tokenManager.clear();
        Toast.makeText(this, "已退出登录", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }

    private void updatePermissionStatus() {
        boolean notificationAccessEnabled = isNotificationListenerEnabled();
        updatePermissionItem(binding.iconNotificationAccess, binding.statusNotificationAccess,
                notificationAccessEnabled, notificationAccessEnabled ? "已授权" : "未授权");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            boolean postNotificationsGranted = ContextCompat.checkSelfPermission(this,
                    Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED;
            updatePermissionItem(binding.iconPostNotifications, binding.statusPostNotifications,
                    postNotificationsGranted, postNotificationsGranted ? "已授权" : "未授权");
            binding.permissionPostNotifications.setVisibility(View.VISIBLE);
        } else {
            binding.permissionPostNotifications.setVisibility(View.GONE);
        }

        boolean batteryOptimized = isBatteryOptimizationEnabled();
        updatePermissionItem(binding.iconBattery, binding.statusBattery,
                !batteryOptimized, batteryOptimized ? "未授权" : "已授权");
    }

    private void updatePermissionItem(ImageView icon, TextView status, boolean granted, String statusText) {
        if (granted) {
            icon.setImageResource(android.R.drawable.checkbox_on_background);
            icon.setColorFilter(ContextCompat.getColor(this, android.R.color.holo_green_dark));
        } else {
            icon.setImageResource(android.R.drawable.ic_dialog_info);
            icon.setColorFilter(ContextCompat.getColor(this, android.R.color.holo_red_dark));
        }
        status.setText(statusText);
    }

    private boolean isNotificationListenerEnabled() {
        String flat = Settings.Secure.getString(getContentResolver(), "enabled_notification_listeners");
        return flat != null && flat.contains(getPackageName());
    }

    private boolean isBatteryOptimizationEnabled() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
            return pm != null && !pm.isIgnoringBatteryOptimizations(getPackageName());
        }
        return false;
    }

    private void requestBatteryOptimization() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);
            } catch (Exception e) {
                startActivity(new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS));
            }
        }
    }
}
