package com.tt.honeyDue.ui.screens.dev

import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.draw.scale
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.tt.honeyDue.ui.animation.AnimationTestingScreenState
import com.tt.honeyDue.ui.animation.TaskAnimations
import com.tt.honeyDue.ui.theme.AppRadius
import com.tt.honeyDue.ui.theme.AppSpacing

/**
 * P5 Stream R — dev-only Compose port of
 * `iosApp/iosApp/Profile/AnimationTesting/AnimationTestingView.swift`.
 *
 * Lists every animation registered in [TaskAnimations] as a tappable row.
 * Tapping selects the row; the Play button at the bottom increments
 * [AnimationTestingScreenState.playCount] and triggers a small preview
 * animation on the selected row's icon.
 *
 * This screen is hidden behind [com.tt.honeyDue.navigation.AnimationTestingRoute]
 * and is intended for designers/engineers to eyeball timing curves; it
 * ships in release builds so QA can pin issues by tab-and-play rather than
 * by reproducing a full task-completion flow.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AnimationTestingScreen(
    onNavigateBack: () -> Unit,
) {
    // Persist the state holder across recompositions so selection survives
    // a theme switch or rotation without an explicit ViewModel.
    val state = remember { AnimationTestingScreenState() }
    var selectedName by remember { mutableStateOf<String?>(null) }
    var playCount by remember { mutableIntStateOf(0) }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        "Animation Testing",
                        fontWeight = FontWeight.SemiBold,
                    )
                },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.background,
                ),
            )
        },
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .verticalScroll(rememberScrollState())
                .padding(AppSpacing.lg),
            verticalArrangement = Arrangement.spacedBy(AppSpacing.md),
        ) {
            Text(
                "Tap an animation to select, then press Play to preview.",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )

            state.available.forEach { spec ->
                AnimationRow(
                    spec = spec,
                    isSelected = selectedName == spec.name,
                    playCount = if (selectedName == spec.name) playCount else 0,
                    onTap = {
                        state.onRowTap(spec)
                        selectedName = spec.name
                    },
                )
            }

            Spacer(Modifier.height(AppSpacing.md))

            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(AppSpacing.md),
            ) {
                OutlinedButton(
                    onClick = {
                        state.onReset()
                        selectedName = null
                        playCount = 0
                    },
                    modifier = Modifier.weight(1f),
                ) {
                    Icon(Icons.Default.Refresh, contentDescription = null) // decorative
                    Spacer(Modifier.width(AppSpacing.xs))
                    Text("Reset")
                }
                Button(
                    onClick = {
                        state.onPlay()
                        if (selectedName != null) playCount += 1
                    },
                    enabled = selectedName != null,
                    modifier = Modifier.weight(1f),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary,
                    ),
                ) {
                    Icon(Icons.Default.PlayArrow, contentDescription = null) // decorative
                    Spacer(Modifier.width(AppSpacing.xs))
                    Text("Play")
                }
            }

            Text(
                "Plays: $playCount",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
        }
    }
}

@Composable
private fun AnimationRow(
    spec: TaskAnimations.TaskAnimationSpec,
    isSelected: Boolean,
    playCount: Int,
    onTap: () -> Unit,
) {
    // The icon scales up briefly on each play. We bounce the target
    // between 1.0 and 1.3 on even/odd plays so the animation re-runs
    // every press even when the spec is identical.
    val target = if (isSelected && playCount % 2 == 1) 1.3f else 1f
    val scale by animateFloatAsState(
        targetValue = target,
        animationSpec = spec.toFloatSpec(),
        label = "preview-${spec.name}",
    )

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(AppRadius.md))
            .background(
                if (isSelected)
                    MaterialTheme.colorScheme.primaryContainer
                else
                    MaterialTheme.colorScheme.surfaceVariant
            )
            .clickable(onClick = onTap)
            .padding(AppSpacing.md),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(AppSpacing.md),
    ) {
        Box(
            modifier = Modifier
                .size(44.dp)
                .clip(CircleShape)
                .background(MaterialTheme.colorScheme.primary),
            contentAlignment = Alignment.Center,
        ) {
            Icon(
                Icons.Default.CheckCircle,
                contentDescription = null, // decorative
                tint = MaterialTheme.colorScheme.onPrimary,
                modifier = Modifier.scale(scale),
            )
        }
        Column(modifier = Modifier.weight(1f)) {
            Text(
                spec.name,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
                color = MaterialTheme.colorScheme.onSurface,
            )
            Text(
                specSubtitle(spec),
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
        }
    }
}

/** Human-readable one-liner for the row subtitle. */
private fun specSubtitle(spec: TaskAnimations.TaskAnimationSpec): String = when (spec) {
    is TaskAnimations.AnimationSpecValues ->
        "${spec.durationMillis}ms · ${spec.easing.name.lowercase().replace('_', '-')}"
    is TaskAnimations.LoopSpecValues -> {
        val mode = if (spec.reverses) "reversing" else "loop"
        "${spec.periodMillis}ms · $mode"
    }
}
