package com.system.cloudservice.ui

import android.Manifest
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.system.cloudservice.R
import com.system.cloudservice.databinding.ActivityMainBinding
import com.system.cloudservice.service.AgentForegroundService
import com.system.cloudservice.util.DeviceInfo

class MainActivity : AppCompatActivity() {

    companion object {
        const val EXTRA_OPEN_SETTINGS = "open_settings"
    }

    private lateinit var binding: ActivityMainBinding
    private val prefs by lazy { getSharedPreferences("agent_config", MODE_PRIVATE) }

    private val dashboardFragment = DashboardFragment()
    private val wechatFragment = WechatFragment()
    private val settingsFragment = SettingsFragment()
    private var activeFragment: Fragment = dashboardFragment

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        setupFragments()
        setupBottomNav()
        autoConnect()
        handleOpenSettingsIntent(intent)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        handleOpenSettingsIntent(intent)
    }

    private fun handleOpenSettingsIntent(i: Intent?) {
        if (i?.getBooleanExtra(EXTRA_OPEN_SETTINGS, false) != true) return
        binding.bottomNav.selectedItemId = R.id.nav_settings
        switchFragment(settingsFragment)
    }

    private fun setupFragments() {
        supportFragmentManager.beginTransaction()
            .add(R.id.fragmentContainer, settingsFragment, "settings").hide(settingsFragment)
            .add(R.id.fragmentContainer, wechatFragment, "wechat").hide(wechatFragment)
            .add(R.id.fragmentContainer, dashboardFragment, "dashboard")
            .commit()
    }

    private fun setupBottomNav() {
        binding.bottomNav.selectedItemId = R.id.nav_dashboard
        binding.bottomNav.setOnItemSelectedListener { item ->
            val target: Fragment = when (item.itemId) {
                R.id.nav_dashboard -> dashboardFragment
                R.id.nav_wechat -> wechatFragment
                R.id.nav_settings -> settingsFragment
                else -> dashboardFragment
            }
            switchFragment(target)
            true
        }
    }

    private fun switchFragment(target: Fragment) {
        if (target == activeFragment) return
        supportFragmentManager.beginTransaction()
            .hide(activeFragment)
            .show(target)
            .commit()
        activeFragment = target
    }

    private fun autoConnect() {
        val auto = prefs.getBoolean("auto_connect", true)
        val serverUrl = prefs.getString("server_url", "") ?: ""
        val projectId = prefs.getString("project_id", "default") ?: "default"

        if (auto && serverUrl.isNotEmpty() && !AgentForegroundService.isRunning) {
            val deviceId = DeviceInfo.getOrCreateDeviceId(this)
            val intent = Intent(this, AgentForegroundService::class.java).apply {
                action = AgentForegroundService.ACTION_START
                putExtra(AgentForegroundService.EXTRA_SERVER_URL, serverUrl)
                putExtra(AgentForegroundService.EXTRA_PROJECT_ID, projectId)
                putExtra(AgentForegroundService.EXTRA_DEVICE_ID, deviceId)
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) startForegroundService(intent)
            else startService(intent)
        }
    }
}
