package io.visus.orbis.feature.orb.ui

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.runtime.CompositionLocalProvider
import io.visus.orbis.core.ui.components.Slider
import io.visus.orbis.core.ui.components.SliderDefaults
import io.visus.orbis.core.ui.LocalContentColor
import io.visus.orbis.core.ui.components.Icon
import io.visus.orbis.core.ui.components.IconButton
import io.visus.orbis.core.ui.components.IconButtonVariant
import io.visus.orbis.core.ui.components.ModalBottomSheet
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import io.visus.orbis.core.ui.OrbisTheme
import io.visus.orbis.core.ui.components.Text

@Composable
fun OrbScreen(
    viewModel: OrbViewModel,
    modifier: Modifier = Modifier
) {
    val uiState by viewModel.uiState.collectAsState()
    val context = LocalContext.current
    var showSettingsSheet by remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        viewModel.initialize(context)
    }

    Box(
        modifier = modifier.fillMaxSize()
    ) {
        // WebGPU Surface (background)
        if (uiState.isInitialized) {
            OrbSurface(
                renderService = viewModel.getRenderService(),
                modifier = Modifier.fillMaxSize()
            )
        }

        // Error message
        uiState.error?.let { error ->
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = error,
                    style = OrbisTheme.typography.body1,
                    color = OrbisTheme.colors.error
                )
            }
        }

        if (uiState.isInitialized) {
            // FPS Counter
            Text(
                text = "${uiState.fps} FPS",
                style = OrbisTheme.typography.label1,
                color = Color.White,
                modifier = Modifier
                    .align(Alignment.TopStart)
                    .statusBarsPadding()
                    .padding(start = 16.dp, top = 16.dp)
            )

            // Settings Icon
            CompositionLocalProvider(LocalContentColor provides Color.White) {
                IconButton(
                    onClick = { showSettingsSheet = true },
                    variant = IconButtonVariant.Ghost,
                    modifier = Modifier
                        .align(Alignment.TopEnd)
                        .statusBarsPadding()
                        .padding(end = 8.dp, top = 8.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Settings,
                        contentDescription = "Settings"
                    )
                }
            }
        }

        ModalBottomSheet(
            isVisible = showSettingsSheet,
            onDismissRequest = { showSettingsSheet = false }
        ) {
            ControlsPanel(
                color = uiState.renderState.color,
                amplitude = uiState.renderState.amplitude,
                onRedChange = viewModel::updateRed,
                onGreenChange = viewModel::updateGreen,
                onBlueChange = viewModel::updateBlue,
                onAlphaChange = viewModel::updateAlpha,
                onAmplitudeChange = viewModel::updateAmplitude,
                modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
            )
        }
    }
}

@Composable
private fun ControlsPanel(
    color: Color,
    amplitude: Float,
    onRedChange: (Float) -> Unit,
    onGreenChange: (Float) -> Unit,
    onBlueChange: (Float) -> Unit,
    onAlphaChange: (Float) -> Unit,
    onAmplitudeChange: (Float) -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier.fillMaxWidth()
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(
                text = "Color",
                style = OrbisTheme.typography.label1,
                color = OrbisTheme.colors.text
            )
            Spacer(modifier = Modifier.width(12.dp))
            Box(
                modifier = Modifier
                    .size(32.dp)
                    .clip(RoundedCornerShape(6.dp))
                    .background(color)
                    .border(
                        width = 1.dp,
                        color = OrbisTheme.colors.outline,
                        shape = RoundedCornerShape(6.dp)
                    )
            )
        }

        Spacer(modifier = Modifier.height(12.dp))

        // RGBA Sliders
        ColorSlider(
            label = "R",
            value = color.red,
            onValueChange = onRedChange,
            trackColor = Color.Red.copy(alpha = 0.3f),
            thumbColor = Color.Red
        )
        ColorSlider(
            label = "G",
            value = color.green,
            onValueChange = onGreenChange,
            trackColor = Color.Green.copy(alpha = 0.3f),
            thumbColor = Color.Green
        )
        ColorSlider(
            label = "B",
            value = color.blue,
            onValueChange = onBlueChange,
            trackColor = Color.Blue.copy(alpha = 0.3f),
            thumbColor = Color.Blue
        )
        ColorSlider(
            label = "A",
            value = color.alpha,
            onValueChange = onAlphaChange,
            trackColor = OrbisTheme.colors.outline,
            thumbColor = OrbisTheme.colors.primary
        )

        Spacer(modifier = Modifier.height(8.dp))

        // Amplitude slider
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(
                text = "Amp",
                style = OrbisTheme.typography.label2,
                color = OrbisTheme.colors.textSecondary,
                modifier = Modifier.width(32.dp)
            )
            Slider(
                value = amplitude,
                onValueChange = onAmplitudeChange,
                valueRange = 0f..2f,
                colors = SliderDefaults.colors(
                    thumbColor = OrbisTheme.colors.primary,
                    activeTrackColor = OrbisTheme.colors.primary,
                    inactiveTrackColor = OrbisTheme.colors.outline
                ),
                modifier = Modifier.weight(1f)
            )
            Text(
                text = "${(amplitude * 100).toInt()}%",
                style = OrbisTheme.typography.label2,
                color = OrbisTheme.colors.textSecondary,
                modifier = Modifier.width(48.dp)
            )
        }
    }
}

@Composable
private fun ColorSlider(
    label: String,
    value: Float,
    onValueChange: (Float) -> Unit,
    trackColor: Color,
    thumbColor: Color,
    modifier: Modifier = Modifier
) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = modifier.fillMaxWidth()
    ) {
        Text(
            text = label,
            style = OrbisTheme.typography.label2,
            color = OrbisTheme.colors.textSecondary,
            modifier = Modifier.width(32.dp)
        )
        Slider(
            value = value,
            onValueChange = onValueChange,
            valueRange = 0f..1f,
            colors = SliderDefaults.colors(
                thumbColor = thumbColor,
                activeTrackColor = thumbColor,
                inactiveTrackColor = trackColor
            ),
            modifier = Modifier.weight(1f)
        )
        Text(
            text = "${(value * 255).toInt()}",
            style = OrbisTheme.typography.label2,
            color = OrbisTheme.colors.textSecondary,
            modifier = Modifier.width(48.dp)
        )
    }
}
