package com.seven.ikar.kotlin.feature.call

import android.Manifest
import android.content.pm.PackageManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Call
import androidx.compose.material.icons.outlined.CallEnd
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Videocam
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
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.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.zIndex
import androidx.core.content.ContextCompat
import com.seven.ikar.kotlin.core.model.CallMediaType
import kotlinx.coroutines.launch
import org.webrtc.SurfaceViewRenderer
import org.webrtc.VideoTrack
import kotlin.math.roundToInt

@Composable
fun CallScreen(
    state: AudioCallSnapshot,
    onAccept: () -> Unit,
    onDecline: () -> Unit,
    onEnd: () -> Unit
) {
    val context = LocalContext.current
    val currentOnAccept by rememberUpdatedState(onAccept)
    val currentMediaType by rememberUpdatedState(state.mediaType)
    val currentContext by rememberUpdatedState(context)
    val incomingPermissionsLauncher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) {
        val hasMicrophone = ContextCompat.checkSelfPermission(
            currentContext,
            Manifest.permission.RECORD_AUDIO
        ) == PackageManager.PERMISSION_GRANTED
        val hasCamera = currentMediaType != CallMediaType.Video ||
            ContextCompat.checkSelfPermission(
                currentContext,
                Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_GRANTED
        if (hasMicrophone && hasCamera) {
            currentOnAccept()
        }
    }

    val handleAccept = {
        val requiredPermissions = buildList {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                add(Manifest.permission.RECORD_AUDIO)
            }
            if (
                state.mediaType == CallMediaType.Video &&
                ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
            ) {
                add(Manifest.permission.CAMERA)
            }
        }

        if (requiredPermissions.isEmpty()) {
            onAccept()
        } else {
            incomingPermissionsLauncher.launch(requiredPermissions.toTypedArray())
        }
    }

    Surface(
        modifier = Modifier.fillMaxSize(),
        color = Color(0xFF081823)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    Brush.verticalGradient(
                        colors = listOf(Color(0xFF0A1F2D), Color(0xFF081823))
                    )
                )
                .padding(horizontal = 24.dp, vertical = 28.dp),
            verticalArrangement = Arrangement.SpaceBetween
        ) {
            Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
                Text(
            text = "ИКАР",
                    style = MaterialTheme.typography.labelLarge,
                    color = Color(0xFF90D6FF)
                )
                Text(
                    text = state.peer.displayName,
                    style = MaterialTheme.typography.headlineMedium,
                    color = Color.White,
                    fontWeight = FontWeight.SemiBold
                )
                Text(
                    text = buildPrimaryStatus(state),
                    style = MaterialTheme.typography.bodyMedium,
                    color = Color(0xFFB2C9D6)
                )
            }

            Column(
                modifier = Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.spacedBy(18.dp)
            ) {
                if (state.mediaType == CallMediaType.Video) {
                    val renderState = state.videoRenderState
                    val previewMarginPx = with(LocalDensity.current) { 16.dp.roundToPx() }
                    var videoStageSize by remember(state.callId) { mutableStateOf(IntSize.Zero) }
                    var localPreviewSize by remember(state.callId) { mutableStateOf(IntSize.Zero) }
                    var localPreviewOffset by remember(state.callId) { mutableStateOf(IntOffset.Zero) }
                    var isLocalPreviewPositionInitialized by remember(state.callId) { mutableStateOf(false) }

                    fun clampLocalPreviewOffset(offset: IntOffset): IntOffset {
                        if (videoStageSize == IntSize.Zero || localPreviewSize == IntSize.Zero) {
                            return IntOffset.Zero
                        }

                        val availableX = (videoStageSize.width - localPreviewSize.width).coerceAtLeast(0)
                        val availableY = (videoStageSize.height - localPreviewSize.height).coerceAtLeast(0)
                        val minX = previewMarginPx.coerceAtMost(availableX)
                        val minY = previewMarginPx.coerceAtMost(availableY)
                        val maxX = (availableX - previewMarginPx).coerceAtLeast(minX)
                        val maxY = (availableY - previewMarginPx).coerceAtLeast(minY)

                        return IntOffset(
                            x = offset.x.coerceIn(minX, maxX),
                            y = offset.y.coerceIn(minY, maxY)
                        )
                    }

                    fun buildDefaultLocalPreviewOffset(): IntOffset =
                        clampLocalPreviewOffset(
                            IntOffset(
                                x = videoStageSize.width - localPreviewSize.width,
                                y = videoStageSize.height - localPreviewSize.height
                            )
                        )

                    LaunchedEffect(videoStageSize, localPreviewSize, previewMarginPx, state.callId) {
                        if (videoStageSize == IntSize.Zero || localPreviewSize == IntSize.Zero) {
                            return@LaunchedEffect
                        }

                        localPreviewOffset = if (isLocalPreviewPositionInitialized) {
                            clampLocalPreviewOffset(localPreviewOffset)
                        } else {
                            isLocalPreviewPositionInitialized = true
                            buildDefaultLocalPreviewOffset()
                        }
                    }

                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(420.dp)
                            .onSizeChanged { videoStageSize = it }
                            .background(Color(0xFF122A39), RoundedCornerShape(28.dp))
                    ) {
                        if (renderState?.eglBaseContext != null && renderState.remoteVideoTrack != null) {
                            CallVideoSurface(
                                eglBaseContext = renderState.eglBaseContext,
                                track = renderState.remoteVideoTrack,
                                isMirrored = false,
                                isOverlay = false,
                                modifier = Modifier.fillMaxSize()
                            )
                        } else {
                            VideoPlaceholder(
                                text = buildStageText(state),
                                modifier = Modifier.fillMaxSize()
                            )
                        }

                        if (renderState?.eglBaseContext != null && renderState.localVideoTrack != null) {
                            CallVideoSurface(
                                eglBaseContext = renderState.eglBaseContext,
                                track = renderState.localVideoTrack,
                                isMirrored = true,
                                isOverlay = true,
                                modifier = Modifier
                                    .zIndex(1f)
                                    .offset { localPreviewOffset }
                                    .onSizeChanged { localPreviewSize = it }
                                    .pointerInput(state.callId, videoStageSize, localPreviewSize) {
                                        detectDragGesturesAfterLongPress(
                                            onDrag = { change, dragAmount ->
                                                change.consume()
                                                isLocalPreviewPositionInitialized = true
                                                localPreviewOffset = clampLocalPreviewOffset(
                                                    IntOffset(
                                                        x = localPreviewOffset.x + dragAmount.x.roundToInt(),
                                                        y = localPreviewOffset.y + dragAmount.y.roundToInt()
                                                    )
                                                )
                                            }
                                        )
                                    }
                                    .fillMaxWidth(0.32f)
                                    .aspectRatio(0.75f)
                            )
                        }
                    }
                } else {
                    Box(
                        modifier = Modifier
                            .size(220.dp)
                            .background(Color(0xFF122A39), CircleShape),
                        contentAlignment = Alignment.Center
                    ) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.spacedBy(10.dp)
                        ) {
                            Icon(
                                imageVector = Icons.Outlined.Call,
                                contentDescription = null,
                                tint = Color.White,
                                modifier = Modifier.size(88.dp)
                            )
                            Text(
                                text = buildStageText(state),
                                color = Color.White,
                                style = MaterialTheme.typography.titleMedium
                            )
                        }
                    }
                }
            }

            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .navigationBarsPadding(),
                verticalArrangement = Arrangement.spacedBy(14.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                if (state.stage == AudioCallStage.Incoming) {
                    IncomingCallSwipeControl(
                        onAccept = handleAccept,
                        onDecline = onDecline
                    )
                    Text(
                        text = "Сдвиньте трубку вправо, чтобы принять, или влево, чтобы отклонить",
                        color = Color(0xFFB2C9D6),
                        style = MaterialTheme.typography.bodySmall
                    )
                } else {
                    CallActionButton(
                        text = if (state.stage == AudioCallStage.Active) "Завершить" else "Отменить",
                        icon = if (state.stage == AudioCallStage.Active) Icons.Outlined.CallEnd else Icons.Outlined.Close,
                        containerColor = Color(0xFFBE2D38),
                        onClick = onEnd
                    )
                }
            }
        }
    }
}

@Composable
private fun IncomingCallSwipeControl(
    onAccept: () -> Unit,
    onDecline: () -> Unit,
    modifier: Modifier = Modifier
) {
    val scope = rememberCoroutineScope()
    var trackWidthPx by remember { mutableStateOf(0f) }
    var handleWidthPx by remember { mutableStateOf(0f) }
    val dragOffsetPx = remember { androidx.compose.animation.core.Animatable(0f) }
    var isCompleting by remember { mutableStateOf(false) }

    val maxTravelPx = ((trackWidthPx - handleWidthPx) / 2f).coerceAtLeast(0f)
    val triggerThresholdPx = maxTravelPx * 0.62f

    Box(
        modifier = modifier
            .fillMaxWidth()
            .height(96.dp)
            .clip(RoundedCornerShape(48.dp))
            .background(Color(0xFF102537))
            .border(1.dp, Color(0xFF1A425B), RoundedCornerShape(48.dp))
            .onSizeChanged { trackWidthPx = it.width.toFloat() }
    ) {
        Row(
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = 22.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            SlideActionHint(
                icon = Icons.Outlined.Close,
                label = "Отклонить",
                color = Color(0xFFFF7A7A),
                alignEnd = false
            )
            SlideActionHint(
                icon = Icons.Outlined.Call,
                label = "Принять",
                color = Color(0xFF75E2A0),
                alignEnd = true
            )
        }

        Box(
            modifier = Modifier
                .align(Alignment.Center)
                .offset { IntOffset(dragOffsetPx.value.roundToInt(), 0) }
                .size(76.dp)
                .onSizeChanged { handleWidthPx = it.width.toFloat() }
                .clip(CircleShape)
                .background(Color.White)
                .pointerInput(maxTravelPx, isCompleting) {
                    if (isCompleting) {
                        return@pointerInput
                    }

                    detectDragGestures(
                        onDragStart = {
                            scope.launch { dragOffsetPx.stop() }
                        },
                        onDragCancel = {
                            scope.launch { dragOffsetPx.animateTo(0f) }
                        },
                        onDragEnd = {
                            if (isCompleting) {
                                return@detectDragGestures
                            }

                            val currentOffset = dragOffsetPx.value
                            when {
                                currentOffset >= triggerThresholdPx -> {
                                    isCompleting = true
                                    scope.launch {
                                        dragOffsetPx.animateTo(maxTravelPx)
                                        onAccept()
                                    }
                                }

                                currentOffset <= -triggerThresholdPx -> {
                                    isCompleting = true
                                    scope.launch {
                                        dragOffsetPx.animateTo(-maxTravelPx)
                                        onDecline()
                                    }
                                }

                                else -> {
                                    scope.launch { dragOffsetPx.animateTo(0f) }
                                }
                            }
                        },
                        onDrag = { change, dragAmount ->
                            if (isCompleting) {
                                return@detectDragGestures
                            }

                            change.consume()
                            val nextOffset = (dragOffsetPx.value + dragAmount.x)
                                .coerceIn(-maxTravelPx, maxTravelPx)
                            scope.launch { dragOffsetPx.snapTo(nextOffset) }
                        }
                    )
                },
            contentAlignment = Alignment.Center
        ) {
            Icon(
                imageVector = Icons.Outlined.Call,
                contentDescription = null,
                tint = if (dragOffsetPx.value >= 0f) Color(0xFF1B7F49) else Color(0xFFAF2330),
                modifier = Modifier.size(34.dp)
            )
        }
    }
}

@Composable
private fun SlideActionHint(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    label: String,
    color: Color,
    alignEnd: Boolean
) {
    Column(
        horizontalAlignment = if (alignEnd) Alignment.End else Alignment.Start,
        verticalArrangement = Arrangement.spacedBy(6.dp)
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            tint = color,
            modifier = Modifier.size(22.dp)
        )
        Text(
            text = label,
            color = color,
            style = MaterialTheme.typography.labelLarge
        )
    }
}

@Composable
private fun CallActionButton(
    text: String,
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    containerColor: Color,
    onClick: () -> Unit
) {
    Button(
        onClick = onClick,
        colors = ButtonDefaults.buttonColors(containerColor = containerColor),
        shape = RoundedCornerShape(26.dp),
        modifier = Modifier.fillMaxWidth()
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            modifier = Modifier.padding(end = 10.dp)
        )
        Text(text)
    }
}

@Composable
private fun VideoPlaceholder(
    text: String,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier,
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Icon(
            imageVector = Icons.Outlined.Videocam,
            contentDescription = null,
            tint = Color.White,
            modifier = Modifier.size(72.dp)
        )
        Text(
            text = text,
            color = Color.White,
            style = MaterialTheme.typography.titleMedium
        )
    }
}

@Composable
private fun CallVideoSurface(
    eglBaseContext: org.webrtc.EglBase.Context,
    track: VideoTrack,
    isMirrored: Boolean,
    isOverlay: Boolean,
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current
    val currentTrack by rememberUpdatedState(track)
    var renderer by remember { mutableStateOf<SurfaceViewRenderer?>(null) }

    AndroidView(
        modifier = modifier,
        factory = { viewContext ->
            SurfaceViewRenderer(viewContext).apply {
                init(eglBaseContext, null)
                setEnableHardwareScaler(true)
                setMirror(isMirrored)
                setZOrderMediaOverlay(isOverlay)
                setBackgroundColor(android.graphics.Color.TRANSPARENT)
                renderer = this
            }
        },
        update = { view ->
            view.setMirror(isMirrored)
            view.setZOrderMediaOverlay(isOverlay)
            if (renderer !== view) {
                renderer = view
            }
        }
    )

    DisposableEffect(renderer, currentTrack) {
        val activeRenderer = renderer
        if (activeRenderer != null) {
            currentTrack.addSink(activeRenderer)
        }

        onDispose {
            if (activeRenderer != null) {
                currentTrack.removeSink(activeRenderer)
            }
        }
    }

    DisposableEffect(context) {
        onDispose {
            renderer?.release()
            renderer = null
        }
    }
}

private fun buildPrimaryStatus(state: AudioCallSnapshot): String =
    state.peer.phoneNumber ?: if (state.mediaType == CallMediaType.Video) "Ikar Video" else "Ikar Audio"

private fun buildStageText(state: AudioCallSnapshot): String = when (state.stage) {
    AudioCallStage.Incoming -> if (state.mediaType == CallMediaType.Video) "Входящий видеозвонок" else "Входящий аудиозвонок"
    AudioCallStage.Outgoing -> "Идёт дозвон..."
    AudioCallStage.Connecting -> "Соединение..."
    AudioCallStage.Active -> if (state.mediaType == CallMediaType.Video) "Видеозвонок ${state.durationText}" else "Разговор ${state.durationText}"
    AudioCallStage.None -> "Звонок"
}
