package club.clubk.ktag.apps.koth

import android.Manifest
import android.content.Context
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import club.clubk.ktag.apps.koth.ui.KothScreen
import club.clubk.ktag.apps.koth.ui.theme.KothTheme

private const val TAG = "KTag KotH"

class KothActivity : ComponentActivity() {

    private val viewModel: KothViewModel by viewModels()

    private val requiredPermissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        arrayOf(
            Manifest.permission.BLUETOOTH_ADVERTISE,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )
    } else {
        arrayOf(
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )
    }

    private val permissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.entries.all { it.value }
        Log.d(TAG, "Permission results: ${permissions.map { "${it.key}: ${it.value}" }}")

        if (allGranted) {
            Log.i(TAG, "All permissions granted")
            showMainContent()
        } else {
            val deniedPermissions = permissions.filter { !it.value }.keys
            Log.w(TAG, "Some permissions denied: $deniedPermissions")
            showPermissionDeniedContent(deniedPermissions.toList())
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(TAG, "onCreate called")

        // Set portrait orientation and keep screen on
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        checkAndRequestPermissions()
    }

    private fun checkAndRequestPermissions() {
        Log.d(TAG, "Checking permissions: ${requiredPermissions.joinToString()}")
        if (hasRequiredPermissions()) {
            Log.i(TAG, "All required permissions already granted")
            showMainContent()
        } else {
            Log.i(TAG, "Requesting permissions")
            requestPermissions()
        }
    }

    private fun hasRequiredPermissions(): Boolean {
        return requiredPermissions.all { permission ->
            ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
        }
    }

    private fun requestPermissions() {
        Log.d(TAG, "Launching permission request")
        permissionLauncher.launch(requiredPermissions)
    }

    private fun showMainContent() {
        setContent {
            KothTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    KothMainScreen(
                        viewModel = viewModel,
                        context = this,
                        onSettingsClick = { openSettings() }
                    )
                }
            }
        }
    }

    private fun showPermissionDeniedContent(deniedPermissions: List<String>) {
        setContent {
            KothTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    PermissionDeniedScreen(
                        deniedPermissions = deniedPermissions,
                        onRequestPermissions = { requestPermissions() }
                    )
                }
            }
        }
    }

    private fun openSettings() {
        val intent = KothSettingsActivity.createIntent(this)
        startActivity(intent)
    }

    override fun onStart() {
        super.onStart()
        if (hasRequiredPermissions()) {
            viewModel.startScanning()
        }
    }

    override fun onStop() {
        super.onStop()
        viewModel.stopScanning()
    }

    override fun onDestroy() {
        super.onDestroy()
        viewModel.cleanup()
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun KothMainScreen(
    viewModel: KothViewModel,
    context: Context,
    onSettingsClick: () -> Unit
) {
    var showMenu by remember { mutableStateOf(false) }

    // Check if game is in an active state where settings/back should be blocked
    val gameState = viewModel.gameState
    val isGameActive = gameState is KothState.Initiating ||
            gameState is KothState.CountingDown ||
            gameState is KothState.Playing

    // Block back button during active game
    BackHandler(enabled = isGameActive) {
        // Do nothing - back is disabled during active game
    }

    // Initialize ViewModel and handle BLE scanning lifecycle
    DisposableEffect(Unit) {
        viewModel.initialize(context)
        viewModel.startScanning()
        onDispose {
            viewModel.stopScanning()
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(stringResource(R.string.app_name)) },
                actions = {
                    // Only show menu when game is not active
                    if (!isGameActive) {
                        IconButton(onClick = { showMenu = true }) {
                            Icon(Icons.Default.MoreVert, contentDescription = "Menu")
                        }
                        DropdownMenu(
                            expanded = showMenu,
                            onDismissRequest = { showMenu = false }
                        ) {
                            DropdownMenuItem(
                                text = { Text(stringResource(R.string.action_settings)) },
                                onClick = {
                                    showMenu = false
                                    onSettingsClick()
                                }
                            )
                        }
                    }
                }
            )
        }
    ) { paddingValues ->
        KothScreen(
            viewModel = viewModel,
            modifier = Modifier.padding(paddingValues)
        )
    }
}

@Composable
fun PermissionDeniedScreen(
    deniedPermissions: List<String>,
    onRequestPermissions: () -> Unit
) {
    Log.d(TAG, "Showing permission denied screen for permissions: $deniedPermissions")
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(
            text = "KTag needs the following permissions to detect devices:",
            style = MaterialTheme.typography.bodyLarge,
            textAlign = TextAlign.Center,
            modifier = Modifier.padding(bottom = 8.dp)
        )
        deniedPermissions.forEach { permission ->
            Text(
                text = "• ${permission.split(".").last()}",
                style = MaterialTheme.typography.bodyMedium,
                textAlign = TextAlign.Center,
                modifier = Modifier.padding(vertical = 4.dp)
            )
        }
        Button(
            onClick = {
                Log.d(TAG, "Permission request button clicked")
                onRequestPermissions()
            },
            modifier = Modifier.padding(top = 16.dp)
        ) {
            Text("Grant Permissions")
        }
    }
}
