@file:Suppress("TooManyFunctions") // Compose screen + private helper composables

package com.fabledsword.minstrel.library.ui

import androidx.compose.animation.Crossfade
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
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.lazy.items as lazyItems
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import com.composables.icons.lucide.ArrowLeft
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.Play
import com.composables.icons.lucide.User
import com.fabledsword.minstrel.library.widgets.AlbumCard
import com.fabledsword.minstrel.library.widgets.ArtistCard
import com.fabledsword.minstrel.models.ArtistRef
import com.fabledsword.minstrel.models.TrackRef
import com.fabledsword.minstrel.models.albumCoverPath
import com.fabledsword.minstrel.nav.AlbumDetail
import com.fabledsword.minstrel.nav.ArtistDetail
import com.fabledsword.minstrel.shared.formatDuration
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow
import com.fabledsword.minstrel.shared.widgets.LikeButton
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ServerImage
import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile
import com.fabledsword.minstrel.shared.widgets.TrackRow

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ArtistDetailScreen(
    navController: NavHostController,
    viewModel: ArtistDetailViewModel = hiltViewModel(),
    playerViewModel: com.fabledsword.minstrel.player.ui.PlayerViewModel = hiltViewModel(),
) {
    val state by viewModel.uiState.collectAsStateWithLifecycle()
    val snackbarHostState = remember { SnackbarHostState() }
    LaunchedEffect(Unit) {
        viewModel.transientMessages.collect { msg ->
            snackbarHostState.showSnackbar(msg)
        }
    }
    Scaffold(
        contentWindowInsets = ShellContentWindowInsets,
        modifier = Modifier.fillMaxSize(),
        topBar = {
            TopAppBar(
                title = { Text(titleFor(state)) },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Lucide.ArrowLeft, contentDescription = "Back")
                    }
                },
            )
        },
        snackbarHost = { SnackbarHost(snackbarHostState) },
    ) { inner ->
        PullToRefreshScaffold(
            onRefresh = { viewModel.refresh().join() },
            modifier = Modifier.fillMaxSize().padding(inner),
        ) {
            // Crossfade keyed on `state::class` so a Success → fresh
            // Success refresh (same kind, new detail) doesn't re-fade
            // the body; only Loading ↔ Success ↔ Error animate.
            Crossfade(targetState = state::class, label = "artist-detail") { _ ->
                when (val s = state) {
                    is ArtistDetailUiState.Loading ->
                        if (s.seed != null) {
                            SeededArtistLoading(s.seed)
                        } else {
                            SkeletonArtistAlbumsGrid()
                        }
                    is ArtistDetailUiState.Error -> ErrorRetry(
                        title = "Couldn't load artist",
                        message = s.message,
                        onRetry = { viewModel.refresh() },
                    )
                    is ArtistDetailUiState.Success ->
                        ArtistSuccessBody(s, viewModel, playerViewModel, navController)
                }
            }
        }
    }
}

@Composable
private fun ArtistSuccessBody(
    state: ArtistDetailUiState.Success,
    viewModel: ArtistDetailViewModel,
    playerViewModel: com.fabledsword.minstrel.player.ui.PlayerViewModel,
    navController: NavHostController,
) {
    val artistLiked by viewModel.artistLiked.collectAsStateWithLifecycle()
    val playerState by playerViewModel.uiState.collectAsStateWithLifecycle()
    ArtistBody(
        state = state,
        artistLiked = artistLiked,
        playingTrackId = playerState.currentTrack?.id,
        onPlay = viewModel::playArtist,
        onToggleLike = viewModel::toggleLikeArtist,
        onAlbumClick = { id -> navController.navigate(AlbumDetail(id)) },
        onTopTrackClick = viewModel::playTopTracks,
        onSimilarArtistClick = { id -> navController.navigate(ArtistDetail(id)) },
    )
}

private fun titleFor(state: ArtistDetailUiState): String = when (state) {
    is ArtistDetailUiState.Success -> state.detail.artist.name
    is ArtistDetailUiState.Loading -> state.seed?.name ?: "Artist"
    is ArtistDetailUiState.Error -> "Artist"
}

@Composable
private fun ArtistBody(
    state: ArtistDetailUiState.Success,
    artistLiked: Boolean,
    playingTrackId: String?,
    onPlay: () -> Unit,
    onToggleLike: () -> Unit,
    onAlbumClick: (String) -> Unit,
    onTopTrackClick: (Int) -> Unit,
    onSimilarArtistClick: (String) -> Unit,
) {
    val detail = state.detail
    LazyVerticalGrid(
        columns = GridCells.Adaptive(minSize = 176.dp),
        modifier = Modifier.fillMaxSize(),
        contentPadding = PaddingValues(8.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
    ) {
        item(span = { GridItemSpan(maxLineSpan) }) {
            ArtistHeader(
                artist = detail.artist,
                artistLiked = artistLiked,
                fallbackAlbumId = detail.albums.firstOrNull()?.id,
                onPlay = onPlay,
                onToggleLike = onToggleLike,
            )
        }
        if (state.topTracks.isNotEmpty()) {
            item(span = { GridItemSpan(maxLineSpan) }) {
                TopTracksPanel(
                    tracks = state.topTracks,
                    playingTrackId = playingTrackId,
                    onTrackClick = onTopTrackClick,
                )
            }
        }
        if (state.similarArtists.isNotEmpty()) {
            item(span = { GridItemSpan(maxLineSpan) }) {
                SimilarArtistsStrip(
                    artists = state.similarArtists,
                    onArtistClick = onSimilarArtistClick,
                )
            }
        }
        if (detail.albums.isEmpty()) {
            item(span = { GridItemSpan(maxLineSpan) }) {
                EmptyAlbumsHint()
            }
        } else {
            items(items = detail.albums, key = { it.id }) { album ->
                AlbumCard(album = album, onClick = { onAlbumClick(album.id) })
            }
        }
    }
}

@Composable
private fun TopTracksPanel(
    tracks: List<TrackRef>,
    playingTrackId: String?,
    onTrackClick: (Int) -> Unit,
) {
    Column(modifier = Modifier.fillMaxWidth()) {
        Text(
            text = "Top tracks",
            style = MaterialTheme.typography.titleLarge,
            color = MaterialTheme.colorScheme.onBackground,
            modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
        )
        tracks.forEachIndexed { index, track ->
            TopTrackRow(
                track = track,
                nowPlaying = track.id == playingTrackId,
                onClick = { onTrackClick(index) },
            )
        }
    }
}

@Composable
private fun TopTrackRow(
    track: TrackRef,
    nowPlaying: Boolean,
    onClick: () -> Unit,
) {
    TrackRow(
        title = track.title,
        artist = track.artistName,
        trackId = track.id,
        onClick = onClick,
        nowPlaying = nowPlaying,
        trailing = {
            Text(
                text = formatDuration(track.durationSec, zero = "--:--"),
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(start = 12.dp),
            )
        },
    )
}

@Composable
private fun SimilarArtistsStrip(
    artists: List<ArtistRef>,
    onArtistClick: (String) -> Unit,
) {
    HorizontalScrollRow(title = "Similar artists") {
        lazyItems(items = artists, key = { it.id }) { artist ->
            ArtistCard(
                artist = artist,
                onClick = { onArtistClick(artist.id) },
            )
        }
    }
}

@Composable
private fun ArtistHeader(
    artist: ArtistRef,
    artistLiked: Boolean,
    fallbackAlbumId: String?,
    onPlay: () -> Unit,
    onToggleLike: () -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        ArtistAvatar(artist, fallbackAlbumId)
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = artist.name,
                style = MaterialTheme.typography.headlineSmall,
                color = MaterialTheme.colorScheme.onBackground,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis,
            )
            if (artist.albumCount > 0) {
                Text(
                    text = albumCountLine(artist),
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }
        }
        LikeButton(liked = artistLiked, onToggle = onToggleLike)
        Button(onClick = onPlay) {
            Icon(Lucide.Play, contentDescription = null, modifier = Modifier.size(18.dp))
            Spacer(Modifier.width(8.dp))
            Text("Play")
        }
    }
}

@Composable
private fun ArtistAvatar(artist: ArtistRef, fallbackAlbumId: String? = null) {
    // Server coverUrl wins; otherwise mirror the server's "use the
    // first album's cover" rule via the loaded album list (Flutter
    // _ArtistAvatar). Bare Lucide.User only when neither exists.
    val model = when {
        artist.coverUrl.isNotEmpty() -> artist.coverUrl
        fallbackAlbumId != null -> albumCoverPath(fallbackAlbumId)
        else -> null
    }
    Box(
        modifier = Modifier
            .size(96.dp)
            .clip(CircleShape)
            .background(MaterialTheme.colorScheme.surfaceVariant),
        contentAlignment = Alignment.Center,
    ) {
        ServerImage(
            url = model,
            contentDescription = artist.name,
            modifier = Modifier.fillMaxSize(),
        ) {
            Icon(
                imageVector = Lucide.User,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.size(40.dp),
            )
        }
    }
}

private fun albumCountLine(artist: ArtistRef): String =
    if (artist.albumCount == 1) "1 album" else "${artist.albumCount} albums"

@Composable
private fun EmptyAlbumsHint() {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Text(
            text = "No albums yet for this artist.",
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
        )
        Spacer(Modifier.height(4.dp))
        Text(
            text = "They might still be importing or the scan hasn't picked them up.",
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
        )
    }
}

private const val SKELETON_ARTIST_GRID_TILES = 9

@Composable
private fun SkeletonArtistAlbumsGrid() {
    LazyVerticalGrid(
        columns = GridCells.Adaptive(minSize = 176.dp),
        contentPadding = PaddingValues(8.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        modifier = Modifier.fillMaxSize(),
    ) {
        items(SKELETON_ARTIST_GRID_TILES) { SkeletonAlbumTile() }
    }
}

/**
 * Loading body that renders the artist header from the navigation
 * seed (avatar + name + album count) with a skeleton album grid
 * below until the fetch lands. Play / Like omitted — they need the
 * loaded detail.
 */
@Composable
private fun SeededArtistLoading(seed: ArtistRef) {
    LazyVerticalGrid(
        columns = GridCells.Adaptive(minSize = 176.dp),
        contentPadding = PaddingValues(8.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        modifier = Modifier.fillMaxSize(),
    ) {
        item(span = { GridItemSpan(maxLineSpan) }) {
            Row(
                modifier = Modifier.fillMaxWidth().padding(8.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(12.dp),
            ) {
                ArtistAvatar(seed)
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = seed.name,
                        style = MaterialTheme.typography.headlineSmall,
                        color = MaterialTheme.colorScheme.onBackground,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis,
                    )
                    if (seed.albumCount > 0) {
                        Text(
                            text = albumCountLine(seed),
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                        )
                    }
                }
            }
        }
        items(SKELETON_ARTIST_GRID_TILES) { SkeletonAlbumTile() }
    }
}
