package dev.adriankuta.visualizer

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
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.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import dev.adriankuta.visualizer.ui.theme.VisualizerTheme

/**
 * Entry point activity that hosts the Compose UI for the audio visualizer demo.
 *
 * Sets up the app theme, window insets, and renders [VisualizerScreen].
 */
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            VisualizerTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    VisualizerScreen(modifier = Modifier.padding(innerPadding))
                }
            }
        }
    }
}

/**
 * Top-level screen that manages permission requests and lifecycle of [VisualizerController],
 * and renders the waveform, FFT bars, and simple metrics with control buttons.
 *
 * @param modifier Modifier applied to the screen container.
 */
@Composable
private fun VisualizerScreen(modifier: Modifier = Modifier) {
    val context = LocalContext.current
    var permissionGranted by remember {
        mutableStateOf(
            ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.RECORD_AUDIO
            ) == PackageManager.PERMISSION_GRANTED
        )
    }

    val requestPermissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission()
    ) { granted ->
        permissionGranted = granted
    }

    var waveform by remember { mutableStateOf<ByteArray?>(null) }
    var fft by remember { mutableStateOf<ByteArray?>(null) }

    val controller = remember(permissionGranted) {
        VisualizerController(
            audioSessionId = 0,
            onWaveform = { data -> waveform = data.clone() },
            onFft = { data -> fft = data.clone() }
        )
    }

    val lifecycleOwner = LocalLifecycleOwner.current

    DisposableEffect(lifecycleOwner, permissionGranted, controller) {
        val observer = LifecycleEventObserver { _, event ->
            if (!permissionGranted) return@LifecycleEventObserver
            when (event) {
                Lifecycle.Event.ON_START -> runCatching { controller.start() }
                Lifecycle.Event.ON_STOP -> runCatching { controller.stop() }
                else -> {}
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        // If permission has just been granted while we are already STARTED/RESUMED,
        // ensure the visualizer starts immediately (ON_START won't be called again).
        if (permissionGranted && lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
            runCatching { controller.start() }
        }
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
            runCatching { controller.stop() }
        }
    }

    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.Start
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .verticalScroll(rememberScrollState())
        ) {
            Text("Android Visualizer Demo", style = MaterialTheme.typography.headlineSmall)
            Spacer(Modifier.height(8.dp))
            if (!permissionGranted) {
                dev.adriankuta.visualizer.components.PermissionSection(
                    permissionGranted = false,
                    requestPermissionLauncher = requestPermissionLauncher
                )
                return@Column
            }

            Text("Listening to global output. Play music in another app to see data.")
            Spacer(Modifier.height(8.dp))

            dev.adriankuta.visualizer.components.WaveformView(data = waveform)

            Spacer(Modifier.height(8.dp))

            dev.adriankuta.visualizer.components.FftBarsView(data = fft)

            Spacer(Modifier.height(12.dp))
            HorizontalDivider()
            Spacer(Modifier.height(12.dp))

            dev.adriankuta.visualizer.components.MetricsSection(
                waveform = waveform,
                fft = fft
            )
        }
        dev.adriankuta.visualizer.components.ControlButtons(
            onStart = { runCatching { controller.start() } },
            onStop = { runCatching { controller.stop() } },
            modifier = Modifier.align(Alignment.CenterHorizontally)
        )
    }
}


/**
 * Preview of [VisualizerScreen] for Android Studio without runtime data.
 */
@Preview(showBackground = true)
@Composable
fun VisualizerPreview() {
    VisualizerTheme {
        VisualizerScreen()
    }
}