package dev.kaizen.app.live

import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import dev.kaizen.app.R
import dev.kaizen.app.chat.KaizenOrb
import dev.kaizen.app.ui.effect.GlassSurface
import dev.kaizen.app.ui.effect.KaizenShadows
import dev.kaizen.app.ui.icon.KaizenIcons
import dev.kaizen.app.ui.shape.KaizenShapes
import dev.kaizen.app.ui.theme.LocalKaizenAccent

@Composable
fun LiveCallOverlay(
    status: CallStatus,
    subtitle: String,
    amplitude: Float,
    userSpeaking: Boolean,
    elapsedMs: Long,
    onEndCall: () -> Unit,
    onInterrupt: () -> Unit,
    modifier: Modifier = Modifier,
) {
    val isDark = isSystemInDarkTheme()
    val accent = LocalKaizenAccent.current
    val cs = MaterialTheme.colorScheme

    Box(
        modifier
            .fillMaxSize()
            .background(
                if (isDark) Color.Black.copy(alpha = 0.85f)
                else Color.White.copy(alpha = 0.88f)
            )
            .statusBarsPadding()
            .navigationBarsPadding(),
        contentAlignment = Alignment.Center,
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(24.dp),
            modifier = Modifier.fillMaxWidth().padding(horizontal = 32.dp),
        ) {
            // ─── Duration ─────────────────────────────────────────
            val elapsed = elapsedMs / 1000
            val min = elapsed / 60
            val sec = elapsed % 60
            Text(
                String.format("%d:%02d", min, sec),
                color = cs.onSurface.copy(alpha = 0.5f),
                fontSize = 14.sp,
                fontWeight = FontWeight.W400,
                letterSpacing = 1.sp,
            )

            // ─── Orb ──────────────────────────────────────────────
            val isActive = status == CallStatus.LISTENING || status == CallStatus.SPEAKING
            Box(
                Modifier
                    .size(180.dp)
                    .then(
                        if (status == CallStatus.SPEAKING) {
                            Modifier.clickable(
                                interactionSource = remember { MutableInteractionSource() },
                                indication = null,
                                onClick = onInterrupt,
                            )
                        } else Modifier
                    ),
                contentAlignment = Alignment.Center,
            ) {
                KaizenOrb(
                    size = 160.dp,
                    streaming = status == CallStatus.SPEAKING,
                    recording = status == CallStatus.LISTENING && userSpeaking,
                    amplitude = if (isActive) amplitude else null,
                )
            }

            // ─── Status text ──────────────────────────────────────
            val statusText = when (status) {
                CallStatus.IDLE -> ""
                CallStatus.CONNECTING -> stringResource(R.string.live_connecting)
                CallStatus.LISTENING -> if (userSpeaking) stringResource(R.string.live_listening)
                                        else stringResource(R.string.live_ready)
                CallStatus.SPEAKING -> stringResource(R.string.live_speaking)
            }

            Text(
                statusText,
                color = when (status) {
                    CallStatus.SPEAKING -> accent.primary
                    CallStatus.LISTENING -> if (userSpeaking) accent.primary.copy(alpha = 0.8f)
                                            else cs.onSurface.copy(alpha = 0.4f)
                    else -> cs.onSurface.copy(alpha = 0.4f)
                },
                fontSize = 13.sp,
                fontWeight = FontWeight.W400,
                letterSpacing = 0.5.sp,
            )

            // ─── Subtitle (transcript / KI response) ─────────────
            AnimatedVisibility(
                visible = subtitle.isNotEmpty(),
                enter = fadeIn(tween(200)) + expandVertically(),
                exit = fadeOut(tween(150)) + shrinkVertically(),
            ) {
                Text(
                    subtitle,
                    color = cs.onSurface.copy(alpha = 0.75f),
                    fontSize = 15.sp,
                    fontWeight = FontWeight.W300,
                    textAlign = TextAlign.Center,
                    maxLines = 4,
                    overflow = TextOverflow.Ellipsis,
                    lineHeight = 22.sp,
                    modifier = Modifier.fillMaxWidth(),
                )
            }

            Spacer(Modifier.height(32.dp))

            // ─── End Call button ──────────────────────────────────
            EndCallButton(onClick = onEndCall)
        }
    }
}

@Composable
private fun EndCallButton(onClick: () -> Unit) {
    val interaction = remember { MutableInteractionSource() }
    val pressed by interaction.collectIsPressedAsState()
    val pressScale by animateFloatAsState(if (pressed) 0.9f else 1f, label = "end")

    Box(
        Modifier
            .size(64.dp)
            .scale(pressScale)
            .clip(KaizenShapes.circle)
            .background(
                Brush.verticalGradient(
                    listOf(
                        Color(0xFFEF4444),
                        Color(0xFFDC2626),
                    )
                )
            )
            .clickable(interactionSource = interaction, indication = null, onClick = onClick),
        contentAlignment = Alignment.Center,
    ) {
        Icon(
            KaizenIcons.PhoneOff,
            contentDescription = stringResource(R.string.live_end),
            tint = Color.White,
            modifier = Modifier.size(28.dp),
        )
    }
}
