package com.pixelized.desktop.lwa.ui.composable.scene.debug

import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.round
import com.pixelized.desktop.lwa.ui.composable.scene.camera.Camera
import com.pixelized.desktop.lwa.ui.composable.scene.cursor.Cursor
import com.pixelized.desktop.lwa.ui.composable.scene.utils.local
import com.pixelized.desktop.lwa.ui.theme.lwa
import com.pixelized.desktop.lwa.ui.theme.typography.LwaTypography

@Composable
fun CursorDebugPanel(
    modifier: Modifier = Modifier,
    style: LwaTypography.Debug = MaterialTheme.lwa.typography.debug,
    padding: Dp = MaterialTheme.lwa.dimen.debug.offset,
    spacing: Dp = 2.dp,
    camera: Camera,
    cursors: List<Cursor>,
    isOpen: Boolean = true,
) {
    val isOpen = remember { mutableStateOf(isOpen) }

    Column(
        modifier = Modifier
            .clickable { isOpen.value = isOpen.value.not() }
            .widthIn(min = MaterialTheme.lwa.dimen.debug.panelWidth)
            .animateContentSize()
            .then(other = modifier),
        verticalArrangement = Arrangement.spacedBy(space = spacing),
    ) {
        Text(
            style = MaterialTheme.lwa.typography.debug.title,
            color = MaterialTheme.lwa.colorScheme.base.primary,
            text = "Cursor",
        )
        if (isOpen.value) {
            cursors.forEach { cursor ->
                Text(
                    modifier = Modifier.padding(start = padding),
                    style = MaterialTheme.lwa.typography.debug.propertyValue,
                    text = buildAnnotatedString {
                        withStyle(style.propertyIdSpan) { append("global: ") }
                        append(cursor.offset.toString())
                    },
                )
                Text(
                    modifier = Modifier.padding(start = padding),
                    style = MaterialTheme.lwa.typography.debug.propertyValue,
                    text = buildAnnotatedString {
                        withStyle(style.propertyIdSpan) { append("local: ") }
                        append(cursor.offset.local(camera).round().toString())
                    },
                )
            }
        }
    }
}