package eu.gaudian.translator.view.vocabulary.card

import androidx.compose.animation.core.exponentialDecay
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.AnchoredDraggableDefaults
import androidx.compose.foundation.gestures.AnchoredDraggableState
import androidx.compose.foundation.gestures.DraggableAnchors
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.anchoredDraggable
import androidx.compose.foundation.gestures.animateTo
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
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.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
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.graphics.vector.ImageVector
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import eu.gaudian.translator.R
import eu.gaudian.translator.view.composable.AppIcons
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlin.math.roundToInt

private enum class DragState { Minimized, Extended }

@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun DraggableActionPanel(
    modifier: Modifier = Modifier,
    isOpen: Boolean,
    onDismiss: () -> Unit,
    isEditing: Boolean,
    onEditClick: () -> Unit,
    onStatisticsClick: () -> Unit,
    onMoveToCategoryClick: () -> Unit,
    onMoveToStageClick: () -> Unit,
    onDeleteClick: () -> Unit,
    showAnalyzeGrammarButton: Boolean,
    onAnalyzeGrammarClick: () -> Unit,
) {
    val density = LocalDensity.current

    val positionalThreshold = { totalDistance: Float -> totalDistance * 0.5f }
    val velocityThreshold = { with(density) { 125.dp.toPx() } }

    @Suppress("DEPRECATION") val state: AnchoredDraggableState<DragState> = remember {
        AnchoredDraggableState(
            initialValue = DragState.Minimized,
            anchors = DraggableAnchors {
                DragState.Extended at 0f
                DragState.Minimized at 1000f // Initial off-screen position
            },
            positionalThreshold = positionalThreshold,
            velocityThreshold = velocityThreshold,
            snapAnimationSpec = tween(),
            decayAnimationSpec = exponentialDecay()
        )
    }

    var panelWidth by remember { mutableFloatStateOf(0f) }
    val isExtended = state.targetValue == DragState.Extended

    LaunchedEffect(panelWidth) {
        if (panelWidth > 0) {
            val anchors = DraggableAnchors {
                DragState.Extended at 0f
                DragState.Minimized at panelWidth
            }
            if (state.anchors != anchors) {
                state.updateAnchors(anchors)
            }
        }
    }

    LaunchedEffect(isOpen) {
        if (isOpen) {
            state.animateTo(DragState.Extended)
        } else {
            state.animateTo(DragState.Minimized)
        }
    }

    LaunchedEffect(state) {
        snapshotFlow { state.currentValue }
            .distinctUntilChanged()
            .collectLatest {
                if (it == DragState.Minimized) {
                    onDismiss()
                }
            }
    }

    Card(
        shape = RoundedCornerShape(topStart = 20.dp, bottomStart = 20.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
        modifier = modifier
            .padding(vertical = 16.dp)
            .widthIn(min = 64.dp, max = 250.dp)
            .onSizeChanged {
                panelWidth = it.width.toFloat()
            }
            .offset {
                val xOffset = if (state.anchors.size > 0) state.requireOffset() else 0f
                IntOffset(x = xOffset.roundToInt(), y = 0)
            }
            .anchoredDraggable(
                state = state,
                orientation = Orientation.Horizontal,
                flingBehavior = AnchoredDraggableDefaults.flingBehavior(
                    state = state,
                    positionalThreshold = positionalThreshold,
                )
            )
    ) {
        Row(modifier.padding(8.dp)) {
            // Thumb indicator
            Surface(
                modifier = Modifier
                    .height(75.dp)
                    .width(4.dp)
                    .align(Alignment.CenterVertically),
                color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.3f),
                shape = RoundedCornerShape(2.dp)
            ) {}
            Column(
                modifier = Modifier
                    .fillMaxHeight()
                    .verticalScroll(rememberScrollState())
                    .padding(horizontal = 8.dp),
                horizontalAlignment = Alignment.Start,
                verticalArrangement = Arrangement.Center
            ) {

                val actionClickHandler: (() -> Unit) -> () -> Unit = { action ->
                    {
                        action()
                        onDismiss()
                    }
                }

                if (!isEditing) {
                    ActionItem(icon = AppIcons.Edit, label = stringResource(R.string.edit), isExtended = isExtended, onClick = actionClickHandler(onEditClick))

                    if (showAnalyzeGrammarButton) {
                        ActionItem(
                            icon = AppIcons.AI,
                            label = stringResource(R.string.label_analyze_grammar),
                            isExtended = isExtended,
                            onClick = actionClickHandler(onAnalyzeGrammarClick)
                        )
                    }

                    ActionItem(icon = AppIcons.Category, label = stringResource(R.string.move_to_category), isExtended = isExtended, onClick = actionClickHandler(onMoveToCategoryClick))
                    ActionItem(icon = AppIcons.Stages, label = stringResource(R.string.move_to_stage), isExtended = isExtended, onClick = actionClickHandler(onMoveToStageClick))
                    ActionItem(icon = AppIcons.Statistics, label = stringResource(R.string.label_statistics), isExtended = isExtended, onClick = actionClickHandler(onStatisticsClick))


                    ActionItem(icon = AppIcons.Delete, stringResource(R.string.label_delete), isExtended = isExtended, onClick = actionClickHandler(onDeleteClick))
                }
            }
        }
    }
}

@Composable
private fun ActionItem(
    icon: ImageVector,
    label: String,
    isExtended: Boolean,
    onClick: () -> Unit,
    isLoading: Boolean = false,
    isActive: Boolean = false
) {
    val shape = RoundedCornerShape(12.dp)
    val backgroundColor = if (isActive) {
        MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.6f)
    } else {
        Color.Transparent
    }

    Row(
        modifier = Modifier
            .clip(shape)
            .background(backgroundColor)
            .clickable(onClick = onClick, enabled = !isLoading)
            .padding(vertical = 8.dp, horizontal = 12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        if (isLoading) {
            CircularProgressIndicator(
                modifier = Modifier.size(24.dp),
                color = MaterialTheme.colorScheme.primary,
                strokeWidth = 2.5.dp
            )
        } else {
            Icon(icon, contentDescription = label)
        }
        if (isExtended) {
            Spacer(modifier = Modifier.width(8.dp))
            Text(text = label, style = MaterialTheme.typography.bodyMedium)
        }
    }
}

@Preview
@Composable
fun DraggableActionPanelPreview() {
    DraggableActionPanel(
        isOpen = true,
        onDismiss = {},
        isEditing = false,
        onEditClick = {},

        onStatisticsClick = {},
        onMoveToCategoryClick = {},
        onMoveToStageClick = {},
        onDeleteClick = {},
        showAnalyzeGrammarButton = true,
        onAnalyzeGrammarClick = {}
    )
}