package com.miraclegarden.smsmessage.Activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.WindowManager;
import android.widget.ScrollView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.miraclegarden.library.app.MiracleGardenActivity;
import com.miraclegarden.smsmessage.App;
import com.miraclegarden.smsmessage.AppConfig;
import com.miraclegarden.smsmessage.MessageLogStore;
import com.miraclegarden.smsmessage.databinding.ActivityNotificationBinding;
import com.miraclegarden.smsmessage.network.TokenManager;
import com.miraclegarden.smsmessage.service.NotificationService;
import com.miraclegarden.smsmessage.service.RetryManager;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;

public class NotificationActivity extends MiracleGardenActivity<ActivityNotificationBinding> {

    private static final int MAX_LOG_LINES = 200;
    private static WeakReference<NotificationActivity> instanceRef;

    private TokenManager tokenManager;
    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            restoreLogFromStore();
        }
    };

    private void restoreLogFromStore() {
        if (binding == null || binding.tvLog == null) {
            return;
        }
        binding.tvLog.setText(MessageLogStore.getDisplayText(this));
        binding.scrollView.post(() ->
                binding.scrollView.fullScroll(ScrollView.FOCUS_DOWN));
    }

    public static void sendMessage(String str) {
        Context appContext = App.getAppContext();
        if (appContext != null) {
            MessageLogStore.append(appContext, str);
        }

        NotificationActivity activity = instanceRef != null ? instanceRef.get() : null;
        if (activity != null && activity.handler != null) {
            Message message = Message.obtain();
            message.obj = str;
            activity.handler.sendMessage(message);
        }
    }

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

        tokenManager = TokenManager.getInstance(this);
        // 调试用：暂时跳过登录
//        if (!tokenManager.isLoggedIn()) {
//            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
//            startActivity(new Intent(this, LoginActivity.class));
//            finish();
//            return;
//        }

        instanceRef = new WeakReference<>(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        initView();
        restoreLogFromStore();
    }

    @Override
    protected void onResume() {
        super.onResume();
        restoreLogFromStore();
        updateUI();
        handler.post(statsUpdateRunnable);
    }

    @Override
    protected void onPause() {
        super.onPause();
        handler.removeCallbacks(statsUpdateRunnable);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        if (instanceRef != null && instanceRef.get() == this) {
            instanceRef = null;
        }
    }

    private void initView() {
        if (AppConfig.ENABLE_SERVER_UPLOAD) {
            String username = tokenManager.getUsername();
            if (username != null) {
                binding.tvUsername.setText(username);
            }
        } else {
            binding.tvUsername.setVisibility(android.view.View.GONE);
        }

        if (!AppConfig.ENABLE_SERVER_UPLOAD) {
            binding.tvUploadedCount.setVisibility(android.view.View.GONE);
            binding.tvSuccessRate.setVisibility(android.view.View.GONE);
        }

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

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

        binding.btnClearLog.setOnClickListener(v -> {
            MessageLogStore.clear(this);
            binding.tvLog.setText("");
        });

        binding.btnToggleMonitor.setOnClickListener(v -> toggleMonitoring());
    }

    private void toggleMonitoring() {
        if (!isNotificationListenerEnabled()) {
            Toast.makeText(this, "请先开启通知访问权限", Toast.LENGTH_LONG).show();
            startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));
            return;
        }

        if (NotificationService.isMonitoringActive(this)) {
            NotificationService.stopMonitoring(this);
            sendMessage("正在停止监听...");
        } else {
            if (App.getNotiList(this).isEmpty()) {
                Toast.makeText(this, "请先在\"监听设置\"中添加要监听的APP", Toast.LENGTH_LONG).show();
                return;
            }
            NotificationService.requestStartMonitoring(this);
            sendMessage("正在开启监听服务...");
            updateUI();
        }
    }

    public static void updateUI() {
        NotificationActivity activity = instanceRef != null ? instanceRef.get() : null;
        if (activity == null || activity.binding == null) {
            return;
        }

        if (NotificationService.isMonitoringActive(activity)) {
            activity.binding.btnToggleMonitor.setText("停止监听");
            activity.binding.btnToggleMonitor.setEnabled(true);
            activity.binding.btnToggleMonitor.setBackgroundTintList(
                    android.content.res.ColorStateList.valueOf(0xFFFF5252));
            activity.binding.tvStatus.setText("状态: 监听中");
            activity.binding.tvStatus.setTextColor(0xFF4CAF50);
        } else {
            activity.binding.btnToggleMonitor.setText("开始监听");
            activity.binding.btnToggleMonitor.setEnabled(true);
            activity.binding.btnToggleMonitor.setBackgroundTintList(
                    android.content.res.ColorStateList.valueOf(activity.getResources().getColor(com.miraclegarden.smsmessage.R.color.purple_500)));
            activity.binding.tvStatus.setText("状态: 未启动");
            activity.binding.tvStatus.setTextColor(0xFF888888);
        }
        activity.updateStatistics();
    }

    private void updateStatistics() {
        if (binding == null) {
            return;
        }

        android.content.SharedPreferences sp = getSharedPreferences("server", MODE_PRIVATE);
        int totalCount = sp.getInt("total_count", 0);
        int uploadedCount = sp.getInt("uploaded_count", 0);
        int configuredCount = App.getNotiList(this).size();

        binding.tvConfiguredApps.setText("已配置: " + configuredCount + "个");
        binding.tvMonitoredCount.setText("已抓取: " + totalCount);

        if (AppConfig.ENABLE_SERVER_UPLOAD) {
            binding.tvUploadedCount.setText("上传: " + uploadedCount);
            if (totalCount > 0) {
                int successRate = (uploadedCount * 100) / totalCount;
                binding.tvSuccessRate.setText("成功率: " + successRate + "%");
            } else {
                binding.tvSuccessRate.setText("成功率: --");
            }
        }
    }

    private final Runnable statsUpdateRunnable = new Runnable() {
        @Override
        public void run() {
            updateStatistics();
            handler.postDelayed(this, 2000);
        }
    };

    private void trimLogIfNeeded() {
        if (binding == null || binding.tvLog == null) return;
        String fullText = binding.tvLog.getText().toString();
        String[] lines = fullText.split("\n");
        if (lines.length > MAX_LOG_LINES) {
            StringBuilder sb = new StringBuilder();
            for (int i = lines.length - MAX_LOG_LINES; i < lines.length; i++) {
                sb.append(lines[i]);
                if (i < lines.length - 1) {
                    sb.append("\n");
                }
            }
            binding.tvLog.setText(sb.toString());
        }
    }

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