package com.radiola.ui.recordings

import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
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.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.Pause
import com.composables.icons.lucide.Play
import com.composables.icons.lucide.RotateCcw
import com.composables.icons.lucide.RotateCw
import com.radiola.domain.model.Recording
import com.radiola.ui.theme.Motion
import com.radiola.ui.theme.RadiolaTheme
import com.radiola.ui.theme.pressScale
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * Контент нижнего листа (bottom sheet) для воспроизведения записи эфира.
 * Оборачивать в [ModalBottomSheet] на стороне вызывающего.
 */
@Composable
fun RecordingPlayerSheet(
    recording: Recording,
    onDismiss: () -> Unit,
    viewModel: RecordingPlayerViewModel
) {
    val isPlaying by viewModel.isPlaying.collectAsState()
    val positionMs by viewModel.positionMs.collectAsState()
    val durationMs by viewModel.durationMs.collectAsState()
    val haptic = LocalHapticFeedback.current
    val colors = RadiolaTheme.colors
    val dateFormat = remember { SimpleDateFormat("dd.MM.yyyy HH:mm", Locale.getDefault()) }

    // Запуск воспроизведения при открытии листа
    LaunchedEffect(recording) {
        viewModel.play(recording)
    }

    val landscape = com.radiola.ui.util.isLandscape()
    val effectiveDuration = durationMs.coerceAtLeast(recording.duration ?: 1L).coerceAtLeast(1L)

    val headerSection: @Composable () -> Unit = {
        // Метка «ЗАПИСЬ ЭФИРА»
        Text(
            text = "ЗАПИСЬ ЭФИРА",
            style = MaterialTheme.typography.labelSmall.copy(
                letterSpacing = 2.sp,
                fontWeight = FontWeight.SemiBold
            ),
            color = colors.accent
        )
        Spacer(modifier = Modifier.height(12.dp))
        // Название станции
        Text(
            text = recording.stationName,
            style = MaterialTheme.typography.headlineSmall,
            color = colors.textPrimary,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
        Spacer(modifier = Modifier.height(4.dp))
        // Трек (если есть) + дата
        val meta = buildString {
            if (!recording.trackName.isNullOrBlank()) {
                append(recording.trackName)
                append("  ·  ")
            }
            append(dateFormat.format(Date(recording.startTime)))
        }
        Text(
            text = meta,
            style = MaterialTheme.typography.bodySmall,
            color = colors.textMuted,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }

    val seekSection: @Composable () -> Unit = {
        // Seekbar
        Slider(
            value = positionMs.toFloat(),
            onValueChange = { viewModel.seekTo(it.toLong()) },
            valueRange = 0f..effectiveDuration.toFloat(),
            modifier = Modifier.fillMaxWidth(),
            colors = SliderDefaults.colors(
                thumbColor = colors.accent,
                activeTrackColor = colors.accent,
                inactiveTrackColor = colors.surface2
            )
        )
        // Время: текущее и общее
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(
                text = formatMs(positionMs),
                style = MaterialTheme.typography.labelSmall,
                color = colors.textMuted
            )
            Text(
                text = formatMs(effectiveDuration),
                style = MaterialTheme.typography.labelSmall,
                color = colors.textMuted
            )
        }
    }

    val controlsSection: @Composable () -> Unit = {
        // Ряд управления: rewind15, play/pause, forward15
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(32.dp)
        ) {
            // Перемотка назад на 15 секунд
            IconButton(
                onClick = { viewModel.rewind15() },
                modifier = Modifier.size(48.dp)
            ) {
                Icon(
                    imageVector = Lucide.RotateCcw,
                    contentDescription = "Назад 15 сек",
                    tint = colors.textSecondary,
                    modifier = Modifier.size(24.dp)
                )
            }

            // Кнопка play/pause
            val playInteraction = remember { MutableInteractionSource() }
            Box(
                modifier = Modifier
                    .size(64.dp)
                    .clip(CircleShape)
                    .pressScale(interactionSource = playInteraction),
                contentAlignment = Alignment.Center
            ) {
                Button(
                    onClick = {
                        haptic.performHapticFeedback(HapticFeedbackType.LongPress)
                        viewModel.togglePlayPause()
                    },
                    modifier = Modifier.fillMaxSize(),
                    shape = CircleShape,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = colors.accent,
                        contentColor = colors.bgBase
                    ),
                    contentPadding = PaddingValues(0.dp),
                    interactionSource = playInteraction
                ) {
                    Crossfade(
                        targetState = isPlaying,
                        animationSpec = tween(Motion.Fast),
                        label = "playPauseCrossfade"
                    ) { playing ->
                        Icon(
                            imageVector = if (playing) Lucide.Pause else Lucide.Play,
                            contentDescription = if (playing) "Пауза" else "Воспроизвести",
                            modifier = Modifier.size(28.dp)
                        )
                    }
                }
            }

            // Перемотка вперёд на 15 секунд
            IconButton(
                onClick = { viewModel.forward15() },
                modifier = Modifier.size(48.dp)
            ) {
                Icon(
                    imageVector = Lucide.RotateCw,
                    contentDescription = "Вперёд 15 сек",
                    tint = colors.textSecondary,
                    modifier = Modifier.size(24.dp)
                )
            }
        }
    }

    // Заголовок + строки списка треков. modifier — чтобы в альбоме правая
    // панель скроллилась отдельно.
    val markersSection: @Composable (Modifier) -> Unit = { listModifier ->
        if (recording.markers.isNotEmpty()) {
            Column(modifier = listModifier) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "Треки в записи",
                        style = MaterialTheme.typography.titleSmall,
                        color = colors.textPrimary,
                        fontWeight = FontWeight.SemiBold
                    )
                    Text(
                        text = "${recording.markers.size}",
                        style = MaterialTheme.typography.labelMedium,
                        color = colors.textMuted
                    )
                }
                Spacer(modifier = Modifier.height(8.dp))
                // Индекс текущего трека: последняя метка, до которой уже дошло время
                val activeIndex = recording.markers.indexOfLast { positionMs >= it.offsetMs }
                recording.markers.forEachIndexed { index, marker ->
                    MarkerRow(
                        timecode = formatMs(marker.offsetMs),
                        title = marker.title,
                        active = index == activeIndex,
                        onClick = {
                            haptic.performHapticFeedback(HapticFeedbackType.LongPress)
                            viewModel.seekTo(marker.offsetMs)
                        }
                    )
                }
            }
        }
    }

    if (landscape) {
        // Альбом: слева управление, справа — прокручиваемый список треков.
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .navigationBarsPadding()
                .padding(horizontal = 24.dp)
                .padding(top = 8.dp, bottom = 16.dp)
        ) {
            Column(
                modifier = Modifier.weight(0.5f),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                headerSection()
                Spacer(modifier = Modifier.height(20.dp))
                seekSection()
                Spacer(modifier = Modifier.height(20.dp))
                controlsSection()
            }
            if (recording.markers.isNotEmpty()) {
                Spacer(modifier = Modifier.width(24.dp))
                markersSection(
                    Modifier
                        .weight(0.5f)
                        .verticalScroll(rememberScrollState())
                )
            }
        }
    } else {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                // Отступ под системную навигацию — иначе список треков уходит под кнопки
                .navigationBarsPadding()
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 24.dp)
                .padding(bottom = 16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Spacer(modifier = Modifier.height(8.dp))
            headerSection()
            Spacer(modifier = Modifier.height(24.dp))
            seekSection()
            Spacer(modifier = Modifier.height(24.dp))
            controlsSection()
            if (recording.markers.isNotEmpty()) {
                Spacer(modifier = Modifier.height(28.dp))
                markersSection(Modifier.fillMaxWidth())
            }
        }
    }
}

/** Строка трека в записи: тайм-код + название, тап → переход. */
@Composable
private fun MarkerRow(
    timecode: String,
    title: String,
    active: Boolean,
    onClick: () -> Unit
) {
    val colors = RadiolaTheme.colors
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(12.dp))
            .background(if (active) colors.surface2 else androidx.compose.ui.graphics.Color.Transparent)
            .clickable(onClick = onClick)
            .padding(horizontal = 12.dp, vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        Text(
            text = timecode,
            style = MaterialTheme.typography.labelMedium,
            color = if (active) colors.accent else colors.textMuted,
            fontWeight = FontWeight.Medium
        )
        Text(
            text = title.ifBlank { "—" },
            style = MaterialTheme.typography.bodyMedium,
            color = if (active) colors.accent else colors.textPrimary,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
            modifier = Modifier.weight(1f)
        )
    }
}

/** Форматирует миллисекунды в строку mm:ss. */
private fun formatMs(ms: Long): String {
    val totalSeconds = (ms / 1000).coerceAtLeast(0)
    val minutes = totalSeconds / 60
    val seconds = totalSeconds % 60
    return "%02d:%02d".format(minutes, seconds)
}
