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 ReleaseDetailContent(
    uiState: PlayerUiState,
    onBack: () -> Unit,
    onRetry: () -> Unit,
    onMediaImageNeeded: (String?) -> Unit,
    onPlayClick: () -> Unit,
    onShuffleClick: () -> Unit,
    onTrackClick: (TrackCard) -> Unit,
    onToggleLike: (Long) -> Unit,
    onPlayNext: (TrackCard) -> Unit,
    onPlayLast: (TrackCard) -> Unit,
    onShare: (TrackCard) -> Unit,
    onAddToPlaylist: (TrackCard) -> Unit
) {
    val release = uiState.releaseDetail?.release ?: uiState.selectedRelease ?: return
    val releaseImage = mediaImageFor(uiState.mediaImages, release.coverUrl)
    val artists = uiState.releaseDetail?.artists.orEmpty()

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

    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 = "Release",
                style = MaterialTheme.typography.labelLarge,
                color = MaterialTheme.colorScheme.onBackground
            )
        }

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

        ReleaseDetailHero(
            release = release,
            artistsText = releaseArtistsText(artists),
            bitmap = releaseImage,
            onPlayClick = onPlayClick,
            onShuffleClick = onShuffleClick
        )

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

        when {
            uiState.isReleaseDetailLoading && uiState.releaseDetail == null -> ReleaseDetailLoading()
            uiState.releaseDetailError != null && uiState.releaseDetail == null -> ReleaseDetailError(
                message = uiState.releaseDetailError,
                onRetry = onRetry
            )
            uiState.releaseDetail != null -> ReleaseTracksSection(
                tracks = uiState.releaseDetail.tracks,
                likedTrackIds = uiState.likedTrackIds,
                onTrackClick = onTrackClick,
                onToggleLike = onToggleLike,
                onPlayNext = onPlayNext,
                onPlayLast = onPlayLast,
                onShare = onShare,
                onAddToPlaylist = onAddToPlaylist
            )
        }

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

@Composable
internal fun ReleaseDetailHero(
    release: ReleaseCard,
    artistsText: String,
    bitmap: Bitmap?,
    onPlayClick: () -> Unit,
    onShuffleClick: () -> Unit
) {
    Column {
        MediaArtwork(
            title = release.title,
            seedId = release.id,
            bitmap = bitmap,
            modifier = Modifier
                .size(210.dp)
                .align(Alignment.CenterHorizontally),
            cornerRadius = 10
        )
        Spacer(modifier = Modifier.height(22.dp))
        Text(
            text = release.title,
            style = MaterialTheme.typography.headlineMedium,
            color = MaterialTheme.colorScheme.onBackground,
            maxLines = 2,
            overflow = TextOverflow.Ellipsis
        )
        Spacer(modifier = Modifier.height(8.dp))
        Text(
            text = artistsText,
            style = MaterialTheme.typography.bodyLarge,
            color = MaterialTheme.colorScheme.onBackground,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
        Spacer(modifier = Modifier.height(4.dp))
        Text(
            text = releaseMeta(release),
            style = MaterialTheme.typography.bodyMedium,
            color = FurumiTextMuted,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
        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 = "Shuffle",
                selected = false,
                modifier = Modifier.weight(1f),
                onClick = onShuffleClick
            )
        }
    }
}

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

@Composable
internal fun ReleaseDetailError(
    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 release",
                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 ReleaseTracksSection(
    tracks: List<TrackCard>,
    likedTrackIds: Set<Long>,
    onTrackClick: (TrackCard) -> Unit,
    onToggleLike: (Long) -> Unit,
    onPlayNext: (TrackCard) -> Unit,
    onPlayLast: (TrackCard) -> Unit,
    onShare: (TrackCard) -> Unit,
    onAddToPlaylist: (TrackCard) -> Unit
) {
    SectionTitle("Tracks")
    Spacer(modifier = Modifier.height(12.dp))

    if (tracks.isEmpty()) {
        Surface(
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(12.dp),
            color = FurumiSurface,
            border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine)
        ) {
            Text(
                text = "No tracks yet",
                modifier = Modifier.padding(16.dp),
                style = MaterialTheme.typography.bodyMedium,
                color = FurumiTextMuted
            )
        }
        return
    }

    val groupedTracks = tracks.groupBy { it.discNumber ?: 1 }.toSortedMap()

    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
        groupedTracks.forEach { (discNumber, discTracks) ->
            if (groupedTracks.size > 1) {
                Text(
                    text = "Disc $discNumber",
                    style = MaterialTheme.typography.labelLarge,
                    color = FurumiTextMuted
                )
            }

            discTracks.forEachIndexed { index, track ->
                ReleaseTrackRow(
                    fallbackIndex = index + 1,
                    track = track,
                    isLiked = likedTrackIds.contains(track.id),
                    onTrackClick = onTrackClick,
                    onToggleLike = { onToggleLike(track.id) },
                    onPlayNext = { onPlayNext(track) },
                    onPlayLast = { onPlayLast(track) },
                    onShare = { onShare(track) },
                    onAddToPlaylist = { onAddToPlaylist(track) }
                )
            }
        }
    }
}
