package cy.hexor.furumi.ui.player

import android.content.Intent
import android.graphics.Bitmap
import androidx.activity.compose.BackHandler
import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
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.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import cy.hexor.furumi.domain.model.ArtistCard
import cy.hexor.furumi.domain.model.PlaylistCard
import cy.hexor.furumi.domain.model.ReleaseCard
import cy.hexor.furumi.domain.model.TrackCard
import cy.hexor.furumi.domain.model.ListeningHistoryItem
import cy.hexor.furumi.playback.AudioPlaybackState
import cy.hexor.furumi.ui.theme.FurumiBlack
import cy.hexor.furumi.ui.theme.FurumiElectricCyan
import cy.hexor.furumi.ui.theme.FurumiHotOrange
import cy.hexor.furumi.ui.theme.FurumiLine
import cy.hexor.furumi.ui.theme.FurumiNeonPink
import cy.hexor.furumi.ui.theme.FurumiNeonViolet
import cy.hexor.furumi.ui.theme.FurumiSurface
import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh
import cy.hexor.furumi.ui.theme.FurumiTextMuted
import kotlin.math.roundToInt

@Composable
internal fun ArtistDetailTrackRow(
    index: Int,
    track: TrackCard,
    bitmap: Bitmap?,
    isLiked: Boolean,
    onMediaImageNeeded: (String?) -> Unit,
    onTrackClick: (TrackCard) -> Unit,
    onToggleLike: () -> Unit,
    onPlayNext: () -> Unit,
    onPlayLast: () -> Unit,
    onShare: () -> Unit,
    onAddToPlaylist: () -> Unit
) {
    var menuExpanded by remember { mutableStateOf(false) }
    val isUnavailable = track.isUnavailableForPlayback()
    val contentAlpha = if (isUnavailable) UNAVAILABLE_TRACK_ALPHA else 1f
    val primaryColor = if (isUnavailable) {
        FurumiTextMuted.copy(alpha = 0.72f)
    } else {
        MaterialTheme.colorScheme.onBackground
    }
    val secondaryColor = FurumiTextMuted.copy(alpha = contentAlpha)

    LaunchedEffect(track.coverUrl) {
        onMediaImageNeeded(track.coverUrl)
    }

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(8.dp))
            .clickable(enabled = !isUnavailable) { onTrackClick(track) }
            .padding(vertical = 2.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = index.toString(),
            modifier = Modifier.width(28.dp),
            style = MaterialTheme.typography.bodyMedium,
            color = secondaryColor
        )
        MediaArtwork(
            title = track.title,
            seedId = track.id,
            bitmap = bitmap,
            modifier = Modifier
                .size(48.dp)
                .unavailableTrackArtworkOverlay(isUnavailable),
            cornerRadius = 6
        )
        Spacer(modifier = Modifier.width(12.dp))
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = track.title,
                style = MaterialTheme.typography.labelLarge,
                color = primaryColor,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = track.artists.joinToString(", ")
                    .ifBlank { track.releaseTitle.orEmpty() }
                    .ifBlank { "Unknown artist" },
                style = MaterialTheme.typography.bodyMedium,
                color = secondaryColor,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
        HeartGlyph(
            isLiked = isLiked,
            modifier = Modifier
                .size(32.dp)
                .clip(CircleShape)
                .clickable(onClick = onToggleLike)
                .padding(4.dp),
            alpha = contentAlpha
        )
        Box {
            MoreDotsGlyph(
                modifier = Modifier
                    .size(32.dp)
                    .clip(CircleShape)
                    .clickable { menuExpanded = true }
                    .padding(4.dp),
                color = FurumiTextMuted.copy(alpha = contentAlpha)
            )
            TrackContextMenu(
                expanded = menuExpanded,
                isLiked = isLiked,
                onDismiss = { menuExpanded = false },
                onToggleLike = { menuExpanded = false; onToggleLike() },
                onPlayNext = { menuExpanded = false; onPlayNext() },
                onPlayLast = { menuExpanded = false; onPlayLast() },
                onShare = { menuExpanded = false; onShare() },
                onAddToPlaylist = { menuExpanded = false; onAddToPlaylist() }
            )
        }
        Spacer(modifier = Modifier.width(4.dp))
        Text(
            text = formatDuration(track.durationSeconds),
            style = MaterialTheme.typography.bodyMedium,
            color = secondaryColor
        )
    }
}

@Composable
internal fun ReleaseTrackRow(
    fallbackIndex: Int,
    track: TrackCard,
    isLiked: Boolean,
    onTrackClick: (TrackCard) -> Unit,
    onToggleLike: () -> Unit,
    onPlayNext: () -> Unit,
    onPlayLast: () -> Unit,
    onShare: () -> Unit,
    onAddToPlaylist: () -> Unit
) {
    var menuExpanded by remember { mutableStateOf(false) }
    val isUnavailable = track.isUnavailableForPlayback()
    val contentAlpha = if (isUnavailable) UNAVAILABLE_TRACK_ALPHA else 1f
    val primaryColor = if (isUnavailable) {
        FurumiTextMuted.copy(alpha = 0.72f)
    } else {
        MaterialTheme.colorScheme.onBackground
    }
    val secondaryColor = FurumiTextMuted.copy(alpha = contentAlpha)

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(8.dp))
            .clickable(enabled = !isUnavailable) { onTrackClick(track) }
            .padding(vertical = 4.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = (track.trackNumber ?: fallbackIndex).toString(),
            modifier = Modifier.width(32.dp),
            style = MaterialTheme.typography.bodyMedium,
            color = secondaryColor
        )
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = track.title,
                style = MaterialTheme.typography.labelLarge,
                color = primaryColor,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = track.artists.joinToString(", ").ifBlank { "Unknown artist" },
                style = MaterialTheme.typography.bodyMedium,
                color = secondaryColor,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
        HeartGlyph(
            isLiked = isLiked,
            modifier = Modifier
                .size(32.dp)
                .clip(CircleShape)
                .clickable(onClick = onToggleLike)
                .padding(4.dp),
            alpha = contentAlpha
        )
        Box {
            MoreDotsGlyph(
                modifier = Modifier
                    .size(32.dp)
                    .clip(CircleShape)
                    .clickable { menuExpanded = true }
                    .padding(4.dp),
                color = FurumiTextMuted.copy(alpha = contentAlpha)
            )
            TrackContextMenu(
                expanded = menuExpanded,
                isLiked = isLiked,
                onDismiss = { menuExpanded = false },
                onToggleLike = { menuExpanded = false; onToggleLike() },
                onPlayNext = { menuExpanded = false; onPlayNext() },
                onPlayLast = { menuExpanded = false; onPlayLast() },
                onShare = { menuExpanded = false; onShare() },
                onAddToPlaylist = { menuExpanded = false; onAddToPlaylist() }
            )
        }
        Spacer(modifier = Modifier.width(4.dp))
        Text(
            text = formatDuration(track.durationSeconds),
            style = MaterialTheme.typography.bodyMedium,
            color = secondaryColor
        )
    }
}

@Composable
internal fun PlaylistTrackRow(
    index: Int,
    track: TrackCard,
    bitmap: Bitmap?,
    isLiked: Boolean,
    onMediaImageNeeded: (String?) -> Unit,
    onTrackClick: (TrackCard) -> Unit,
    onToggleLike: () -> Unit,
    onPlayNext: () -> Unit,
    onPlayLast: () -> Unit,
    onShare: () -> Unit,
    onAddToPlaylist: () -> Unit
) {
    var menuExpanded by remember { mutableStateOf(false) }
    val isUnavailable = track.isUnavailableForPlayback()
    val contentAlpha = if (isUnavailable) UNAVAILABLE_TRACK_ALPHA else 1f
    val primaryColor = if (isUnavailable) {
        FurumiTextMuted.copy(alpha = 0.72f)
    } else {
        MaterialTheme.colorScheme.onBackground
    }
    val secondaryColor = FurumiTextMuted.copy(alpha = contentAlpha)

    LaunchedEffect(track.coverUrl) {
        onMediaImageNeeded(track.coverUrl)
    }

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(8.dp))
            .clickable(enabled = !isUnavailable) { onTrackClick(track) }
            .padding(vertical = 4.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = index.toString(),
            modifier = Modifier.width(28.dp),
            style = MaterialTheme.typography.bodyMedium,
            color = secondaryColor
        )
        MediaArtwork(
            title = track.title,
            seedId = track.id,
            bitmap = bitmap,
            modifier = Modifier
                .size(48.dp)
                .unavailableTrackArtworkOverlay(isUnavailable),
            cornerRadius = 6
        )
        Spacer(modifier = Modifier.width(12.dp))
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = track.title,
                style = MaterialTheme.typography.labelLarge,
                color = primaryColor,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = trackSubtitle(track),
                style = MaterialTheme.typography.bodyMedium,
                color = secondaryColor,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
        HeartGlyph(
            isLiked = isLiked,
            modifier = Modifier
                .size(32.dp)
                .clip(CircleShape)
                .clickable(onClick = onToggleLike)
                .padding(4.dp),
            alpha = contentAlpha
        )
        Box {
            MoreDotsGlyph(
                modifier = Modifier
                    .size(32.dp)
                    .clip(CircleShape)
                    .clickable { menuExpanded = true }
                    .padding(4.dp),
                color = FurumiTextMuted.copy(alpha = contentAlpha)
            )
            TrackContextMenu(
                expanded = menuExpanded,
                isLiked = isLiked,
                onDismiss = { menuExpanded = false },
                onToggleLike = { menuExpanded = false; onToggleLike() },
                onPlayNext = { menuExpanded = false; onPlayNext() },
                onPlayLast = { menuExpanded = false; onPlayLast() },
                onShare = { menuExpanded = false; onShare() },
                onAddToPlaylist = { menuExpanded = false; onAddToPlaylist() }
            )
        }
        Spacer(modifier = Modifier.width(4.dp))
        Text(
            text = formatDuration(track.durationSeconds),
            style = MaterialTheme.typography.bodyMedium,
            color = secondaryColor
        )
    }
}

@Composable
internal fun LibraryRows(
    playlists: List<PlaylistCard>,
    onPlaylistClick: (PlaylistCard) -> Unit
) {
    Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
        playlists.forEach { playlist ->
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(8.dp))
                    .clickable { onPlaylistClick(playlist) },
                verticalAlignment = Alignment.CenterVertically
            ) {
                AlbumArtwork(
                    colors = artistArtworkColors(playlist.id),
                    modifier = Modifier.size(56.dp),
                    cornerRadius = 8
                )
                Spacer(modifier = Modifier.width(12.dp))
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = playlist.title,
                        style = MaterialTheme.typography.labelLarge,
                        color = MaterialTheme.colorScheme.onBackground
                    )
                    Text(
                        text = playlistMeta(playlist),
                        style = MaterialTheme.typography.bodyMedium,
                        color = FurumiTextMuted
                    )
                }
            }
        }
    }
}

@Composable
internal fun QueueTrackRow(
    track: TrackCard,
    bitmap: Bitmap?,
    isLiked: Boolean,
    isPlayed: Boolean = false,
    isCurrent: Boolean = false,
    onMediaImageNeeded: (String?) -> Unit,
    onClick: () -> Unit,
    onToggleLike: () -> Unit,
    onPlayNext: () -> Unit,
    onPlayLast: () -> Unit,
    onShare: () -> Unit,
    onAddToPlaylist: () -> Unit
) {
    var menuExpanded by remember { mutableStateOf(false) }

    LaunchedEffect(track.coverUrl) {
        onMediaImageNeeded(track.coverUrl)
    }

    val contentAlpha = if (isPlayed) 0.5f else 1.0f

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(8.dp))
            .background(if (isCurrent) FurumiSurface else Color.Transparent)
            .clickable(onClick = onClick)
            .padding(vertical = 4.dp, horizontal = if (isCurrent) 8.dp else 0.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Box(contentAlignment = Alignment.Center) {
            MediaArtwork(
                title = track.title,
                seedId = track.id,
                bitmap = bitmap,
                modifier = Modifier
                    .size(48.dp)
                    .drawWithContent {
                        drawContent()
                        if (isPlayed) {
                            drawRect(color = Color.Black.copy(alpha = 0.3f))
                        }
                    },
                cornerRadius = 6
            )
            if (isCurrent) {
                Box(
                    modifier = Modifier
                        .size(48.dp)
                        .background(Color.Black.copy(alpha = 0.4f)),
                    contentAlignment = Alignment.Center
                ) {
                    AudioWaveGlyph(modifier = Modifier.size(20.dp), color = FurumiNeonPink)
                }
            }
        }
        Spacer(modifier = Modifier.width(12.dp))
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = track.title,
                style = if (isCurrent) MaterialTheme.typography.labelLarge.copy(fontWeight = FontWeight.Bold) else MaterialTheme.typography.labelLarge,
                color = if (isCurrent) FurumiNeonPink else MaterialTheme.colorScheme.onBackground.copy(alpha = contentAlpha),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = trackSubtitle(track),
                style = MaterialTheme.typography.bodyMedium,
                color = FurumiTextMuted.copy(alpha = contentAlpha),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
        HeartGlyph(
            isLiked = isLiked,
            modifier = Modifier
                .size(32.dp)
                .clip(CircleShape)
                .clickable(onClick = onToggleLike)
                .padding(4.dp),
            alpha = contentAlpha
        )
        Box {
            MoreDotsGlyph(
                modifier = Modifier
                    .size(32.dp)
                    .clip(CircleShape)
                    .clickable { menuExpanded = true }
                    .padding(4.dp)
            )
            TrackContextMenu(
                expanded = menuExpanded,
                isLiked = isLiked,
                onDismiss = { menuExpanded = false },
                onToggleLike = { menuExpanded = false; onToggleLike() },
                onPlayNext = { menuExpanded = false; onPlayNext() },
                onPlayLast = { menuExpanded = false; onPlayLast() },
                onShare = { menuExpanded = false; onShare() },
                onAddToPlaylist = { menuExpanded = false; onAddToPlaylist() }
            )
        }
        Spacer(modifier = Modifier.width(4.dp))
        Text(
            text = formatDuration(track.durationSeconds),
            style = MaterialTheme.typography.bodyMedium,
            color = FurumiTextMuted.copy(alpha = contentAlpha)
        )
    }
}

private fun TrackCard.isUnavailableForPlayback(): Boolean {
    return streamUrl.isBlank()
}

private fun Modifier.unavailableTrackArtworkOverlay(isUnavailable: Boolean): Modifier {
    if (!isUnavailable) return this
    return drawWithContent {
        drawContent()
        drawRect(color = Color.Black.copy(alpha = 0.44f))
    }
}

private const val UNAVAILABLE_TRACK_ALPHA = 0.42f
