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.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

internal fun artistsSubtitle(uiState: PlayerUiState): String {
    return if (uiState.globalArtistsTotal > 0) {
        pluralCount(uiState.globalArtistsTotal, "artist")
    } else {
        "Artists on this server"
    }
}

internal fun librarySubtitle(uiState: PlayerUiState): String {
    return if (uiState.libraryArtistsTotal > 0) {
        pluralCount(uiState.libraryArtistsTotal, "uploaded artist")
    } else {
        "Your uploads"
    }
}

internal fun pluralCount(count: Long, singular: String): String {
    val label = if (count == 1L) singular else "${singular}s"
    return "$count $label"
}

internal fun pluralCount(count: Int, singular: String): String {
    return pluralCount(count.toLong(), singular)
}

internal fun formatListenedDuration(seconds: Int?): String {
    if (seconds == null || seconds <= 0) return "--"
    val minutes = seconds / 60
    val remainingSeconds = seconds % 60
    return "$minutes:${remainingSeconds.toString().padStart(2, '0')}"
}

internal fun formatDuration(seconds: Int?): String {
    if (seconds == null || seconds <= 0) return "--"
    val minutes = seconds / 60
    val remainingSeconds = seconds % 60
    return "$minutes:${remainingSeconds.toString().padStart(2, '0')}"
}

internal fun formatPlaybackTime(milliseconds: Long): String {
    if (milliseconds <= 0L) return "0:00"
    val totalSeconds = milliseconds / 1_000L
    val minutes = totalSeconds / 60L
    val seconds = totalSeconds % 60L
    return "$minutes:${seconds.toString().padStart(2, '0')}"
}

internal fun trackSubtitle(track: TrackCard): String {
    return track.artists.joinToString(", ")
        .ifBlank { track.releaseTitle.orEmpty() }
        .ifBlank { "Unknown artist" }
}

internal fun releaseMeta(release: ReleaseCard): String {
    val parts = buildList {
        release.year?.let { add(it.toString()) }
        release.releaseType
            ?.replace('_', ' ')
            ?.takeIf { it.isNotBlank() }
            ?.let { add(it) }
        add(pluralCount(release.trackCount, "track"))
    }

    return parts.joinToString(" / ")
}

internal fun releaseArtistsText(artists: List<ArtistCard>): String {
    return artists.joinToString(", ") { it.name }.ifBlank { "Unknown artist" }
}

internal fun playlistMeta(playlist: PlaylistCard): String {
    val parts = buildList {
        add(pluralCount(playlist.trackCount, "track"))
        playlist.ownerName
            ?.takeIf { it.isNotBlank() }
            ?.let { add(it) }
    }

    return parts.joinToString(" / ")
}

internal fun mediaImageFor(mediaImages: Map<String, Bitmap>, url: String?): Bitmap? {
    val imageUrl = url?.takeIf { it.isNotBlank() } ?: return null
    mediaImages[imageUrl]?.let { return it }
    val requestedResource = canonicalMediaImageResource(imageUrl)
    return mediaImages.entries.firstOrNull { (cachedUrl, _) ->
        canonicalMediaImageResource(cachedUrl) == requestedResource
    }?.value
}

internal fun canonicalMediaImageResource(url: String): String {
    val cleanUrl = url.substringBefore('?').trimEnd('/')
    val lastSlash = cleanUrl.lastIndexOf('/')
    if (lastSlash < 0) return cleanUrl

    val variant = cleanUrl.substring(lastSlash + 1).lowercase()
    if (variant !in imageVariantSegments) return cleanUrl

    val withoutVariant = cleanUrl.substring(0, lastSlash)
    val mediaId = withoutVariant.substringAfterLast('/')
    return if (mediaId.toLongOrNull() != null) withoutVariant else cleanUrl
}

internal fun artistArtworkColors(artistId: Long): List<Color> {
    val palettes = listOf(
        listOf(FurumiNeonPink, FurumiNeonViolet, FurumiBlack),
        listOf(FurumiElectricCyan, FurumiSurfaceHigh),
        listOf(FurumiHotOrange, FurumiNeonPink),
        listOf(FurumiNeonViolet, FurumiSurface),
        listOf(FurumiSurfaceHigh, FurumiNeonPink)
    )
    return palettes[paletteIndex(artistId, palettes.size)]
}

internal fun historyArtworkColors(trackId: Long): List<Color> {
    val palettes = listOf(
        listOf(FurumiNeonPink, FurumiNeonViolet, FurumiBlack),
        listOf(FurumiElectricCyan, FurumiSurfaceHigh),
        listOf(FurumiHotOrange, FurumiNeonPink),
        listOf(FurumiNeonViolet, FurumiSurface)
    )
    return palettes[paletteIndex(trackId, palettes.size)]
}

private fun paletteIndex(seedId: Long, paletteCount: Int): Int {
    val remainder = (seedId % paletteCount).toInt()
    return if (remainder >= 0) remainder else remainder + paletteCount
}

internal val imageVariantSegments = setOf("small", "medium", "large")
