package com.tsmobile.app.ui.components

import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.waitForUpOrCancellation
import androidx.compose.foundation.layout.heightIn
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import com.tsmobile.app.ui.theme.UiTokens
import com.tsmobile.app.ui.theme.semanticColors

/**
 * PTT（Push-To-Talk）按住发言按钮。
 *
 * 使用 pointerInput 直接处理按下、松开和取消，确保无需拖动即可发言。
 * 不使用 onClick（PTT 需要区分按下和松开）。
 */
@Composable
fun PTTButton(
    isTransmitting: Boolean,
    onStartTransmit: () -> Unit,
    onStopTransmit: () -> Unit,
    enabled: Boolean = true,
    modifier: Modifier = Modifier,
) {
    val colors = MaterialTheme.colorScheme
    val semanticColors = MaterialTheme.semanticColors
    val currentOnStartTransmit by rememberUpdatedState(onStartTransmit)
    val currentOnStopTransmit by rememberUpdatedState(onStopTransmit)

    Button(
        onClick = {},
        enabled = enabled,
        modifier = modifier
            .heightIn(min = UiTokens.Size.TouchTarget)
            .semantics {
                contentDescription = "按住说话"
                stateDescription = if (isTransmitting) "正在发言" else "未发言"
            }
            .pointerInput(enabled) {
                if (!enabled) return@pointerInput
                awaitEachGesture {
                    awaitFirstDown(requireUnconsumed = false)
                    currentOnStartTransmit()
                    try {
                        waitForUpOrCancellation()
                    } finally {
                        currentOnStopTransmit()
                    }
                }
            },
        colors = ButtonDefaults.buttonColors(
            containerColor = if (isTransmitting) semanticColors.success else colors.primaryContainer,
            contentColor = if (isTransmitting) semanticColors.onSuccess else colors.onPrimaryContainer,
        ),
        elevation = ButtonDefaults.buttonElevation(defaultElevation = UiTokens.Elevation.Subtle),
    ) {
        Text(
            text = if (isTransmitting) "正在发言..." else "按住说话",
            style = MaterialTheme.typography.labelLarge,
        )
    }
}
