package com.miraclegarden.smsmessage.Activity;

import android.Manifest;
import android.content.Intent;
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.ActivityPermissionBinding;
import com.miraclegarden.smsmessage.network.TokenManager;
import com.miraclegarden.smsmessage.util.OEMBackgroundHelper;

public class PermissionActivity extends MiracleGardenActivity<ActivityPermissionBinding> {

    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();
        updatePermissionStatus();
    }

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

        binding.ivBack.setOnClickListener(v -> finish());

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

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

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

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

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

        binding.tvDeviceBrand.setText("设备: " + OEMBackgroundHelper.getManufacturer());
    }

    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) == android.content.pm.PackageManager.PERMISSION_GRANTED;
            updatePermissionItem(binding.iconPostNotifications, binding.statusPostNotifications,
                    postNotificationsGranted, postNotificationsGranted ? "已授权" : "未授权");
            binding.layoutPostNotifications.setVisibility(View.VISIBLE);
        } else {
            binding.layoutPostNotifications.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));
            }
        }
    }
}
