package com.radiola.ui.recordings

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.Crossfade
import androidx.compose.animation.fadeIn
import androidx.compose.animation.slideInVertically
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
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.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.Mic
import com.composables.icons.lucide.Play
import com.composables.icons.lucide.Trash2
import com.radiola.domain.model.Recording
import com.radiola.ui.theme.RadiolaTheme
import com.radiola.ui.theme.pressScale
import com.radiola.ui.components.EmptyState
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.concurrent.TimeUnit

@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class)
@Composable
fun RecordingsScreen(
    viewModel: RecordingsViewModel = hiltViewModel()
) {
    val recordings by viewModel.recordings.collectAsState()
    val isRecording by viewModel.isRecording.collectAsState()
    val colors = RadiolaTheme.colors
    var playing by remember { mutableStateOf<Recording?>(null) }
    // Плеер записи — singleton-контроллер; держим его VM здесь, чтобы корректно
    // ОСТАНОВИТЬ воспроизведение при закрытии шторки и уходе с экрана (иначе
    // аудио продолжает играть без UI и конфликтует с радио).
    val recPlayerVm: RecordingPlayerViewModel = hiltViewModel()
    DisposableEffect(Unit) {
        onDispose { recPlayerVm.close() }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 20.dp)
    ) {
        // Двухцветный заголовок
        Text(
            text = buildAnnotatedString {
                withStyle(SpanStyle(color = colors.textPrimary)) { append("За") }
                withStyle(SpanStyle(color = colors.accent)) { append("писи") }
            },
            style = MaterialTheme.typography.headlineLarge,
            modifier = Modifier.padding(top = 20.dp, bottom = 16.dp)
        )

        // Баннер активной записи
        if (isRecording) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(16.dp))
                    .background(colors.live.copy(alpha = 0.12f))
                    .border(1.dp, colors.live.copy(alpha = 0.4f), RoundedCornerShape(16.dp))
                    .padding(horizontal = 16.dp, vertical = 12.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    // Индикатор записи
                    Box(
                        modifier = Modifier
                            .size(10.dp)
                            .clip(CircleShape)
                            .background(colors.live)
                    )
                    Spacer(modifier = Modifier.width(10.dp))
                    Text(
                        text = "Идёт запись",
                        style = MaterialTheme.typography.labelLarge,
                        color = colors.live
                    )
                }
            }
            Spacer(modifier = Modifier.height(16.dp))
        }

        Crossfade(
            targetState = recordings.isEmpty(),
            label = "recordingsState"
        ) { isEmpty ->
            if (isEmpty) {
                AnimatedVisibility(
                    visible = true,
                    enter = fadeIn() + slideInVertically()
                ) {
                    EmptyState(
                        message = "Нет записей",
                        icon = Lucide.Mic,
                        modifier = Modifier.fillMaxSize()
                    )
                }
            } else {
                LazyColumn(
                    verticalArrangement = Arrangement.spacedBy(10.dp),
                    contentPadding = PaddingValues(bottom = 16.dp)
                ) {
                    items(recordings, key = { it.id }) { recording ->
                        RecordingItem(
                            recording = recording,
                            onPlay = { playing = recording },
                            onDelete = { viewModel.deleteRecording(recording.id) },
                            modifier = Modifier.animateItemPlacement()
                        )
                    }
                }
            }
        }
    }

    // Встроенный плеер в нижнем листе. skipPartiallyExpanded — как у радио-плеера,
    // иначе в partial-режиме navigationBarsPadding не применяется и список треков
    // налезает на системную навигацию.
    playing?.let { rec ->
        ModalBottomSheet(
            onDismissRequest = { recPlayerVm.close(); playing = null },
            sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),
            containerColor = colors.bgBase
        ) {
            RecordingPlayerSheet(
                recording = rec,
                onDismiss = { recPlayerVm.close(); playing = null },
                viewModel = recPlayerVm
            )
        }
    }
}

@Composable
private fun RecordingItem(
    recording: Recording,
    onPlay: () -> Unit,
    onDelete: () -> Unit,
    modifier: Modifier = Modifier
) {
    val colors = RadiolaTheme.colors
    val dateFormat = SimpleDateFormat("dd.MM.yyyy HH:mm", Locale.getDefault())
    val durationText = recording.duration?.let { ms ->
        val minutes = TimeUnit.MILLISECONDS.toMinutes(ms)
        val seconds = TimeUnit.MILLISECONDS.toSeconds(ms) % 60
        String.format("%02d:%02d", minutes, seconds)
    } ?: "??:??"
    val interactionPlay = remember { MutableInteractionSource() }

    Row(
        modifier = modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(16.dp))
            .background(colors.surface)
            .padding(12.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        // Круглая кнопка play
        Box(
            modifier = Modifier
                .size(44.dp)
                .clip(CircleShape)
                .background(colors.surface2)
                .pressScale(interactionSource = interactionPlay)
                .clickable(interactionSource = interactionPlay, indication = null, onClick = onPlay),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                imageVector = Lucide.Play,
                contentDescription = "Воспроизвести",
                tint = colors.accent,
                modifier = Modifier.size(18.dp)
            )
        }

        // Метаданные записи
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = recording.stationName,
                style = MaterialTheme.typography.titleMedium,
                color = colors.textPrimary,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            if (!recording.trackName.isNullOrBlank()) {
                Text(
                    text = recording.trackName,
                    style = MaterialTheme.typography.bodySmall,
                    color = colors.textSecondary,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
            Text(
                text = "${dateFormat.format(Date(recording.startTime))} · $durationText",
                style = MaterialTheme.typography.labelSmall,
                color = colors.textMuted
            )
        }

        // Кнопка удаления
        IconButton(
            onClick = onDelete,
            modifier = Modifier.size(36.dp)
        ) {
            Icon(
                imageVector = Lucide.Trash2,
                contentDescription = "Удалить",
                tint = colors.live,
                modifier = Modifier.size(18.dp)
            )
        }
    }
}
