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

@Composable
internal fun GlobalContent(
    uiState: PlayerUiState,
    onProfileClick: () -> Unit,
    onRetry: () -> Unit,
    onLoadMore: () -> Unit,
    onArtistImageNeeded: (String?) -> Unit,
    onArtistClick: (ArtistCard) -> Unit
) {
    LazyVerticalGrid(
        columns = GridCells.Adaptive(minSize = 148.dp),
        modifier = Modifier.fillMaxSize(),
        contentPadding = PaddingValues(horizontal = 20.dp, vertical = 24.dp),
        horizontalArrangement = Arrangement.spacedBy(14.dp),
        verticalArrangement = Arrangement.spacedBy(18.dp)
    ) {
        item(span = { GridItemSpan(maxLineSpan) }) {
            PlayerHeader(
                title = "Global",
                subtitle = artistsSubtitle(uiState),
                onProfileClick = onProfileClick
            )
        }

        when {
            uiState.isGlobalArtistsLoading && uiState.globalArtists.isEmpty() -> {
                item(span = { GridItemSpan(maxLineSpan) }) { GlobalArtistsLoading() }
            }

            uiState.globalArtistsError != null && uiState.globalArtists.isEmpty() -> {
                item(span = { GridItemSpan(maxLineSpan) }) {
                    GlobalArtistsError(
                        message = uiState.globalArtistsError,
                        onRetry = onRetry
                    )
                }
            }

            uiState.globalArtists.isEmpty() -> {
                item(span = { GridItemSpan(maxLineSpan) }) { GlobalArtistsEmpty() }
            }

            else -> {
                item(span = { GridItemSpan(maxLineSpan) }) {
                    Text(
                        text = "Artists",
                        style = MaterialTheme.typography.titleMedium,
                        color = MaterialTheme.colorScheme.onBackground
                    )
                }

                items(
                    items = uiState.globalArtists,
                    key = { artist -> artist.id }
                ) { artist ->
                    ArtistTile(
                        artist = artist,
                        bitmap = mediaImageFor(uiState.mediaImages, artist.imageUrl),
                        onArtistImageNeeded = onArtistImageNeeded,
                        onClick = { onArtistClick(artist) }
                    )
                }

                item(span = { GridItemSpan(maxLineSpan) }) {
                    GlobalArtistsFooter(
                        uiState = uiState,
                        onLoadMore = onLoadMore
                    )
                }
            }
        }
    }
}

@Composable
internal fun ArtistTile(
    artist: ArtistCard,
    bitmap: Bitmap?,
    onArtistImageNeeded: (String?) -> Unit,
    onClick: () -> Unit
) {
    LaunchedEffect(artist.imageUrl) {
        onArtistImageNeeded(artist.imageUrl)
    }

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(8.dp))
            .clickable(onClick = onClick)
    ) {
        ArtistArtwork(
            artist = artist,
            bitmap = bitmap,
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(1f)
        )
        Spacer(modifier = Modifier.height(10.dp))
        Text(
            text = artist.name,
            style = MaterialTheme.typography.labelLarge,
            color = MaterialTheme.colorScheme.onBackground,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
        Spacer(modifier = Modifier.height(2.dp))
        Text(
            text = "${pluralCount(artist.releaseCount, "release")} / ${pluralCount(artist.trackCount, "track")}",
            style = MaterialTheme.typography.bodyMedium,
            color = FurumiTextMuted,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}

@Composable
internal fun ArtistArtwork(
    artist: ArtistCard,
    bitmap: Bitmap?,
    modifier: Modifier
) {
    MediaArtwork(
        title = artist.name,
        seedId = artist.id,
        bitmap = bitmap,
        modifier = modifier,
        cornerRadius = 8
    )
}

@Composable
internal fun ArtistDetailContent(
    uiState: PlayerUiState,
    onBack: () -> Unit,
    onRetry: () -> Unit,
    onMediaImageNeeded: (String?) -> Unit,
    onPlayClick: () -> Unit,
    onRadioClick: () -> Unit,
    onTrackClick: (TrackCard) -> Unit,
    onReleaseClick: (ReleaseCard) -> Unit,
    onToggleLike: (Long) -> Unit,
    onPlayNext: (TrackCard) -> Unit,
    onPlayLast: (TrackCard) -> Unit,
    onShare: (TrackCard) -> Unit,
    onAddToPlaylist: (TrackCard) -> Unit
) {
    val artist = uiState.artistDetail?.artist ?: uiState.selectedArtist ?: return
    val artistImage = mediaImageFor(uiState.mediaImages, artist.imageUrl)

    LaunchedEffect(artist.imageUrl) {
        onMediaImageNeeded(artist.imageUrl)
    }

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 20.dp, vertical = 20.dp)
    ) {
        Row(
            modifier = Modifier
                .clip(RoundedCornerShape(8.dp))
                .clickable(onClick = onBack)
                .padding(vertical = 8.dp, horizontal = 2.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            BackGlyph(
                modifier = Modifier.size(20.dp),
                color = MaterialTheme.colorScheme.onBackground
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text(
                text = "Artist",
                style = MaterialTheme.typography.labelLarge,
                color = MaterialTheme.colorScheme.onBackground
            )
        }

        Spacer(modifier = Modifier.height(20.dp))

        ArtistDetailHero(
            artist = artist,
            bitmap = artistImage,
            onPlayClick = onPlayClick,
            onRadioClick = onRadioClick
        )

        Spacer(modifier = Modifier.height(28.dp))

        when {
            uiState.isArtistDetailLoading && uiState.artistDetail == null -> ArtistDetailLoading()
            uiState.artistDetailError != null && uiState.artistDetail == null -> ArtistDetailError(
                message = uiState.artistDetailError,
                onRetry = onRetry
            )
            uiState.artistDetail != null -> {
                val detail = uiState.artistDetail
                if (detail.topTracks.isNotEmpty()) {
                    PopularTracksSection(
                        tracks = detail.topTracks,
                        mediaImages = uiState.mediaImages,
                        likedTrackIds = uiState.likedTrackIds,
                        onMediaImageNeeded = onMediaImageNeeded,
                        onTrackClick = onTrackClick,
                        onToggleLike = onToggleLike,
                        onPlayNext = onPlayNext,
                        onPlayLast = onPlayLast,
                        onShare = onShare,
                        onAddToPlaylist = onAddToPlaylist
                    )
                    Spacer(modifier = Modifier.height(28.dp))
                }

                ReleasesSection(
                    releases = detail.releases,
                    mediaImages = uiState.mediaImages,
                    onMediaImageNeeded = onMediaImageNeeded,
                    onReleaseClick = onReleaseClick
                )
            }
        }

        Spacer(modifier = Modifier.height(24.dp))
    }
}

@Composable
internal fun ArtistDetailHero(
    artist: ArtistCard,
    bitmap: Bitmap?,
    onPlayClick: () -> Unit,
    onRadioClick: () -> Unit
) {
    Column {
        MediaArtwork(
            title = artist.name,
            seedId = artist.id,
            bitmap = bitmap,
            modifier = Modifier
                .size(210.dp)
                .align(Alignment.CenterHorizontally),
            cornerRadius = 10
        )
        Spacer(modifier = Modifier.height(22.dp))
        Text(
            text = artist.name,
            style = MaterialTheme.typography.headlineMedium,
            color = MaterialTheme.colorScheme.onBackground,
            maxLines = 2,
            overflow = TextOverflow.Ellipsis
        )
        Spacer(modifier = Modifier.height(8.dp))
        Text(
            text = "${pluralCount(artist.releaseCount, "release")} / ${pluralCount(artist.trackCount, "track")}",
            style = MaterialTheme.typography.bodyMedium,
            color = FurumiTextMuted
        )
        Spacer(modifier = Modifier.height(18.dp))
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            PillAction(
                label = "Play",
                selected = true,
                modifier = Modifier.weight(1f),
                onClick = onPlayClick
            )
            Spacer(modifier = Modifier.width(12.dp))
            PillAction(
                label = "Radio",
                selected = false,
                modifier = Modifier.weight(1f),
                onClick = onRadioClick
            )
        }
    }
}

@Composable
internal fun ArtistDetailLoading() {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(180.dp),
        contentAlignment = Alignment.Center
    ) {
        CircularProgressIndicator(
            color = FurumiNeonPink,
            strokeWidth = 2.dp
        )
    }
}

@Composable
internal fun ArtistDetailError(
    message: String,
    onRetry: () -> Unit
) {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(12.dp),
        color = FurumiSurface,
        border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine)
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Text(
                text = "Could not load artist",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.onBackground
            )
            Spacer(modifier = Modifier.height(6.dp))
            Text(
                text = message,
                style = MaterialTheme.typography.bodyMedium,
                color = FurumiTextMuted
            )
            Spacer(modifier = Modifier.height(14.dp))
            PillAction(
                label = "Retry",
                selected = true,
                onClick = onRetry
            )
        }
    }
}

@Composable
internal fun PopularTracksSection(
    tracks: List<TrackCard>,
    mediaImages: Map<String, Bitmap>,
    likedTrackIds: Set<Long>,
    onMediaImageNeeded: (String?) -> Unit,
    onTrackClick: (TrackCard) -> Unit,
    onToggleLike: (Long) -> Unit,
    onPlayNext: (TrackCard) -> Unit,
    onPlayLast: (TrackCard) -> Unit,
    onShare: (TrackCard) -> Unit,
    onAddToPlaylist: (TrackCard) -> Unit
) {
    SectionTitle("Popular")
    Spacer(modifier = Modifier.height(12.dp))
    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
        tracks.take(5).forEachIndexed { index, track ->
            ArtistDetailTrackRow(
                index = index + 1,
                track = track,
                bitmap = mediaImageFor(mediaImages, track.coverUrl),
                isLiked = likedTrackIds.contains(track.id),
                onMediaImageNeeded = onMediaImageNeeded,
                onTrackClick = onTrackClick,
                onToggleLike = { onToggleLike(track.id) },
                onPlayNext = { onPlayNext(track) },
                onPlayLast = { onPlayLast(track) },
                onShare = { onShare(track) },
                onAddToPlaylist = { onAddToPlaylist(track) }
            )
        }
    }
}

@Composable
internal fun ReleasesSection(
    releases: List<ReleaseCard>,
    mediaImages: Map<String, Bitmap>,
    onMediaImageNeeded: (String?) -> Unit,
    onReleaseClick: (ReleaseCard) -> Unit
) {
    if (releases.isEmpty()) {
        Surface(
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(12.dp),
            color = FurumiSurface,
            border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine)
        ) {
            Text(
                text = "No albums, EPs or singles yet",
                modifier = Modifier.padding(16.dp),
                style = MaterialTheme.typography.bodyMedium,
                color = FurumiTextMuted
            )
        }
        return
    }

    Column(verticalArrangement = Arrangement.spacedBy(28.dp)) {
        releaseSections(releases).forEach { section ->
            Column {
                SectionTitle(section.title)
                Spacer(modifier = Modifier.height(12.dp))
                ReleaseGrid(
                    releases = section.releases,
                    mediaImages = mediaImages,
                    onMediaImageNeeded = onMediaImageNeeded,
                    onReleaseClick = onReleaseClick
                )
            }
        }
    }
}

@Composable
private fun ReleaseGrid(
    releases: List<ReleaseCard>,
    mediaImages: Map<String, Bitmap>,
    onMediaImageNeeded: (String?) -> Unit,
    onReleaseClick: (ReleaseCard) -> Unit
) {
    Column(verticalArrangement = Arrangement.spacedBy(18.dp)) {
        releases.chunked(2).forEach { row ->
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(14.dp)
            ) {
                row.forEach { release ->
                    ReleaseTile(
                        release = release,
                        bitmap = mediaImageFor(mediaImages, release.coverUrl),
                        onMediaImageNeeded = onMediaImageNeeded,
                        onClick = { onReleaseClick(release) },
                        modifier = Modifier.weight(1f)
                    )
                }

                if (row.size == 1) {
                    Spacer(modifier = Modifier.weight(1f))
                }
            }
        }
    }
}

private data class ReleaseSection(
    val key: String,
    val title: String,
    val releases: List<ReleaseCard>
)

private fun releaseSections(releases: List<ReleaseCard>): List<ReleaseSection> {
    val grouped = releases.groupBy { it.releaseType.normalizedReleaseType() }
    val knownSections = releaseTypeOrder.mapNotNull { key ->
        grouped[key]
            ?.takeIf { it.isNotEmpty() }
            ?.let { ReleaseSection(key = key, title = releaseTypeTitle(key), releases = it) }
    }
    val otherSections = grouped
        .filterKeys { it !in releaseTypeOrder }
        .toSortedMap()
        .map { (key, items) ->
            ReleaseSection(key = key, title = releaseTypeTitle(key), releases = items)
        }

    return knownSections + otherSections
}

private fun String?.normalizedReleaseType(): String {
    val value = this
        ?.trim()
        ?.lowercase()
        ?.replace('-', '_')
        ?.takeIf { it.isNotBlank() }
        ?: return RELEASE_TYPE_OTHER

    return when (value) {
        "album", "albums", "lp", "full_length", "full_length_album" -> RELEASE_TYPE_ALBUM
        "ep", "eps", "mini_album", "mini" -> RELEASE_TYPE_EP
        "single", "singles" -> RELEASE_TYPE_SINGLE
        else -> value
    }
}

private fun releaseTypeTitle(type: String): String {
    return when (type) {
        RELEASE_TYPE_ALBUM -> "Albums"
        RELEASE_TYPE_EP -> "EPs"
        RELEASE_TYPE_SINGLE -> "Singles"
        RELEASE_TYPE_OTHER -> "Other"
        else -> type
            .replace('_', ' ')
            .split(' ')
            .joinToString(" ") { word ->
                word.replaceFirstChar { char -> char.titlecase() }
            }
    }
}

private const val RELEASE_TYPE_ALBUM = "album"
private const val RELEASE_TYPE_EP = "ep"
private const val RELEASE_TYPE_SINGLE = "single"
private const val RELEASE_TYPE_OTHER = "other"

private val releaseTypeOrder = listOf(
    RELEASE_TYPE_ALBUM,
    RELEASE_TYPE_EP,
    RELEASE_TYPE_SINGLE
)

@Composable
internal fun ReleaseTile(
    release: ReleaseCard,
    bitmap: Bitmap?,
    onMediaImageNeeded: (String?) -> Unit,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    LaunchedEffect(release.coverUrl) {
        onMediaImageNeeded(release.coverUrl)
    }

    Column(
        modifier = modifier
            .clip(RoundedCornerShape(8.dp))
            .clickable(onClick = onClick)
    ) {
        MediaArtwork(
            title = release.title,
            seedId = release.id,
            bitmap = bitmap,
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(1f),
            cornerRadius = 8
        )
        Spacer(modifier = Modifier.height(10.dp))
        Text(
            text = release.title,
            style = MaterialTheme.typography.labelLarge,
            color = MaterialTheme.colorScheme.onBackground,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
        Spacer(modifier = Modifier.height(2.dp))
        Text(
            text = releaseMeta(release),
            style = MaterialTheme.typography.bodyMedium,
            color = FurumiTextMuted,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}

@Composable
internal fun GlobalArtistsFooter(
    uiState: PlayerUiState,
    onLoadMore: () -> Unit
) {
    when {
        uiState.isGlobalArtistsLoadingMore -> {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(72.dp),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator(
                    color = FurumiNeonPink,
                    strokeWidth = 2.dp,
                    modifier = Modifier.size(24.dp)
                )
            }
        }

        uiState.globalArtistsError != null -> {
            Surface(
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(10.dp),
                color = FurumiSurface,
                border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine)
            ) {
                Row(
                    modifier = Modifier.padding(12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "Could not load more artists",
                        modifier = Modifier.weight(1f),
                        style = MaterialTheme.typography.bodyMedium,
                        color = FurumiTextMuted,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                    Text(
                        text = "Retry",
                        modifier = Modifier
                            .clip(RoundedCornerShape(8.dp))
                            .clickable(onClick = onLoadMore)
                            .padding(horizontal = 10.dp, vertical = 8.dp),
                        style = MaterialTheme.typography.labelLarge,
                        color = FurumiNeonPink
                    )
                }
            }
        }

        uiState.globalArtistsHasMore -> {
            LaunchedEffect(uiState.globalArtists.size, uiState.globalArtistsPage) {
                onLoadMore()
            }

            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(72.dp),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator(
                    color = FurumiNeonPink,
                    strokeWidth = 2.dp,
                    modifier = Modifier.size(24.dp)
                )
            }
        }

        else -> {
            Text(
                text = "${uiState.globalArtists.size} artists loaded",
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 18.dp),
                style = MaterialTheme.typography.labelSmall,
                color = FurumiTextMuted
            )
        }
    }
}

@Composable
internal fun GlobalArtistsLoading() {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(240.dp),
        contentAlignment = Alignment.Center
    ) {
        CircularProgressIndicator(
            color = FurumiNeonPink,
            strokeWidth = 2.dp
        )
    }
}

@Composable
internal fun GlobalArtistsError(
    message: String,
    onRetry: () -> Unit
) {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(12.dp),
        color = FurumiSurface,
        border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine)
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Text(
                text = "Could not load artists",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.onBackground
            )
            Spacer(modifier = Modifier.height(6.dp))
            Text(
                text = message,
                style = MaterialTheme.typography.bodyMedium,
                color = FurumiTextMuted
            )
            Spacer(modifier = Modifier.height(14.dp))
            PillAction(
                label = "Retry",
                selected = true,
                onClick = onRetry
            )
        }
    }
}

@Composable
internal fun GlobalArtistsEmpty() {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(12.dp),
        color = FurumiSurface,
        border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine)
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Text(
                text = "No artists yet",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.onBackground
            )
            Spacer(modifier = Modifier.height(6.dp))
            Text(
                text = "Artists uploaded to this server will appear here.",
                style = MaterialTheme.typography.bodyMedium,
                color = FurumiTextMuted
            )
        }
    }
}
