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.ConnectedDevicesState
import cy.hexor.furumi.domain.model.ConnectedPlaybackState
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
fun PlayerScreen(
    viewModel: PlayerViewModel = hiltViewModel(),
    onLoggedOut: () -> Unit
) {
    val uiState by viewModel.uiState.collectAsState()
    val displayedPlayback = uiState.displayedPlayback()
    var selectedTabName by rememberSaveable { mutableStateOf(PlayerTab.Global.name) }
    val selectedTab = PlayerTab.entries.firstOrNull { it.name == selectedTabName } ?: PlayerTab.Global
    var isProfileMenuOpen by rememberSaveable { mutableStateOf(false) }
    var isFullPlayerOpen by rememberSaveable { mutableStateOf(false) }
    var fullPlayerDragOffset by remember { androidx.compose.runtime.mutableFloatStateOf(0f) }
    var addToPlaylistTrack by remember { mutableStateOf<TrackCard?>(null) }
    var isCreatePlaylistDialogOpen by rememberSaveable { mutableStateOf(false) }
    var createPlaylistTrack by remember { mutableStateOf<TrackCard?>(null) }
    var deletePlaylistCandidate by remember { mutableStateOf<PlaylistCard?>(null) }

    val openCreatePlaylistDialog: (TrackCard?) -> Unit = { track ->
        viewModel.clearPlaylistCreateError()
        createPlaylistTrack = track
        isCreatePlaylistDialogOpen = true
    }

    BackHandler(
        enabled = uiState.selectedPlaylist != null ||
            uiState.selectedRelease != null ||
            uiState.selectedArtist != null ||
            isFullPlayerOpen ||
            isProfileMenuOpen ||
            uiState.isListeningHistoryVisible ||
            addToPlaylistTrack != null ||
            isCreatePlaylistDialogOpen ||
            deletePlaylistCandidate != null
    ) {
        when {
            deletePlaylistCandidate != null -> {
                if (!uiState.isDeletingPlaylist) {
                    deletePlaylistCandidate = null
                }
            }
            isCreatePlaylistDialogOpen -> {
                if (!uiState.isCreatingPlaylist) {
                    isCreatePlaylistDialogOpen = false
                    createPlaylistTrack = null
                }
            }
            addToPlaylistTrack != null -> addToPlaylistTrack = null
            uiState.isListeningHistoryVisible -> viewModel.closeListeningHistory()
            isFullPlayerOpen -> isFullPlayerOpen = false
            uiState.selectedPlaylist != null -> viewModel.closePlaylistDetail()
            uiState.selectedRelease != null -> viewModel.closeReleaseDetail()
            uiState.selectedArtist != null -> viewModel.closeArtistDetail()
            isProfileMenuOpen -> isProfileMenuOpen = false
        }
    }

    val context = LocalContext.current

    LaunchedEffect(uiState.isLoggedOut) {
        if (uiState.isLoggedOut) {
            onLoggedOut()
        }
    }

    LaunchedEffect(Unit) {
        viewModel.shareEvent.collect { url ->
            val sendIntent = Intent(Intent.ACTION_SEND).apply {
                putExtra(Intent.EXTRA_TEXT, url)
                type = "text/plain"
            }
            context.startActivity(Intent.createChooser(sendIntent, "Share track"))
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.background)
            .windowInsetsPadding(WindowInsets.safeDrawing)
    ) {
        Column(modifier = Modifier.fillMaxSize()) {
            Box(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth()
            ) {
                val onProfileClick = { isProfileMenuOpen = !isProfileMenuOpen }
                val artistScrollState = rememberScrollState()
                if (uiState.selectedPlaylist != null) {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .verticalScroll(rememberScrollState())
                    ) {
                        PlaylistDetailContent(
                            uiState = uiState,
                            onBack = viewModel::closePlaylistDetail,
                            onRetry = viewModel::retryPlaylistDetail,
                            onMediaImageNeeded = viewModel::loadMediaImage,
                            onPlayClick = {
                                viewModel.playPlaylistTracks(shuffle = false)
                            },
                            onShuffleClick = {
                                viewModel.playPlaylistTracks(shuffle = true)
                            },
                            onTrackClick = { track ->
                                viewModel.playTrack(track, uiState.playlistDetail?.tracks.orEmpty())
                            },
                            onToggleLike = viewModel::toggleLike,
                            onPlayNext = viewModel::addToPlayNext,
                            onPlayLast = viewModel::addToQueueEnd,
                            onShare = viewModel::shareTrack,
                            onAddToPlaylist = { track -> addToPlaylistTrack = track },
                            onDeletePlaylistClick = { playlist ->
                                viewModel.clearPlaylistDeleteError()
                                deletePlaylistCandidate = playlist
                            }
                        )
                    }
                } else if (uiState.selectedRelease != null) {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .verticalScroll(rememberScrollState())
                    ) {
                        ReleaseDetailContent(
                            uiState = uiState,
                            onBack = viewModel::closeReleaseDetail,
                            onRetry = viewModel::retryReleaseDetail,
                            onMediaImageNeeded = viewModel::loadMediaImage,
                            onPlayClick = {
                                viewModel.playReleaseTracks(shuffle = false)
                            },
                            onShuffleClick = {
                                viewModel.playReleaseTracks(shuffle = true)
                            },
                            onTrackClick = { track ->
                                viewModel.playTrack(track, uiState.releaseDetail?.tracks.orEmpty())
                            },
                            onToggleLike = viewModel::toggleLike,
                            onPlayNext = viewModel::addToPlayNext,
                            onPlayLast = viewModel::addToQueueEnd,
                            onShare = viewModel::shareTrack,
                            onAddToPlaylist = { track -> addToPlaylistTrack = track }
                        )
                    }
                } else if (uiState.selectedArtist != null) {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .verticalScroll(artistScrollState)
                    ) {
                        ArtistDetailContent(
                            uiState = uiState,
                            onBack = viewModel::closeArtistDetail,
                            onRetry = viewModel::retryArtistDetail,
                            onMediaImageNeeded = viewModel::loadMediaImage,
                            onPlayClick = {
                                viewModel.playArtistTracks(shuffle = false)
                            },
                            onRadioClick = {
                                viewModel.playArtistTracks(shuffle = true)
                            },
                            onTrackClick = { track ->
                                viewModel.playTrack(track, uiState.artistDetail?.topTracks.orEmpty())
                            },
                            onReleaseClick = viewModel::openRelease,
                            onToggleLike = viewModel::toggleLike,
                            onPlayNext = viewModel::addToPlayNext,
                            onPlayLast = viewModel::addToQueueEnd,
                            onShare = viewModel::shareTrack,
                            onAddToPlaylist = { track -> addToPlaylistTrack = track }
                        )
                    }
                } else {
                    when (selectedTab) {
                        PlayerTab.Global -> GlobalContent(
                            uiState = uiState,
                            onProfileClick = onProfileClick,
                            onRetry = viewModel::retryGlobalArtists,
                            onLoadMore = viewModel::loadMoreGlobalArtists,
                            onArtistImageNeeded = viewModel::loadMediaImage,
                            onArtistClick = viewModel::openArtist
                        )
                        PlayerTab.Search -> Box(
                            modifier = Modifier
                                .fillMaxSize()
                                .verticalScroll(rememberScrollState())
                        ) {
                            SearchContent(
                                uiState = uiState,
                                onProfileClick = onProfileClick,
                                onQueryChange = viewModel::onSearchQueryChange,
                                onRetry = viewModel::retrySearch,
                                onArtistClick = viewModel::openArtist,
                                onMediaImageNeeded = viewModel::loadMediaImage,
                                onTrackClick = { track ->
                                    viewModel.playTrack(track, uiState.searchResults?.tracks.orEmpty())
                                },
                                onToggleLike = viewModel::toggleLike,
                                onPlayNext = viewModel::addToPlayNext,
                                onPlayLast = viewModel::addToQueueEnd,
                                onShare = viewModel::shareTrack,
                                onAddToPlaylist = { track -> addToPlaylistTrack = track }
                            )
                        }
                        PlayerTab.Library -> Box(
                            modifier = Modifier.fillMaxSize()
                        ) {
                            LibraryContent(
                                uiState = uiState,
                                onProfileClick = onProfileClick,
                                onLoadLibrary = viewModel::loadLibraryIfNeeded,
                                onRetryPlaylists = viewModel::loadPlaylists,
                                onRetryArtists = viewModel::retryLibraryArtists,
                                onLoadMoreArtists = viewModel::loadMoreLibraryArtists,
                                onCreatePlaylistClick = { openCreatePlaylistDialog(null) },
                                onPlaylistPreviewNeeded = viewModel::loadPlaylistPreview,
                                onPlaylistClick = viewModel::openPlaylist,
                                onArtistImageNeeded = viewModel::loadMediaImage,
                                onArtistClick = viewModel::openArtist
                            )
                        }
                    }
                }
            }

            displayedPlayback.currentTrack?.let { track ->
                NowPlayingBar(
                    playback = displayedPlayback,
                    coverBitmap = mediaImageFor(uiState.mediaImages, track.coverUrl),
                    isLiked = uiState.likedTrackIds.contains(track.id),
                    onMediaImageNeeded = viewModel::loadMediaImage,
                    onClick = {
                        isFullPlayerOpen = true
                        fullPlayerDragOffset = 0f
                    },
                    onPlayPause = viewModel::togglePlayPause,
                    onPrevious = viewModel::previousTrack,
                    onNext = viewModel::nextTrack,
                    onToggleShuffle = viewModel::toggleShuffle,
                    onCycleRepeatMode = viewModel::cycleRepeatMode,
                    onToggleLike = { viewModel.toggleLike(track.id) }
                )
            }
            BottomPlayerNav(
                selectedTab = selectedTab,
                onTabSelected = {
                    selectedTabName = it.name
                    viewModel.closePlaylistDetail()
                    viewModel.closeArtistDetail()
                }
            )
        }

        if (isProfileMenuOpen) {
            ProfileMenu(
                uiState = uiState,
                onHistoryClick = {
                    isProfileMenuOpen = false
                    viewModel.openListeningHistory()
                },
                onDeviceClick = viewModel::setActiveDevice,
                onOfflineModeChange = viewModel::setOfflineModeEnabled,
                onSaveListenedChange = viewModel::setSaveListenedTracksEnabled,
                onStorageLimitChange = viewModel::setOfflineStorageLimit,
                onSyncOffline = viewModel::syncOfflineLibrary,
                onClearOfflineCache = viewModel::clearOfflineCache,
                onLogout = viewModel::logout,
                modifier = Modifier
                    .align(Alignment.TopCenter)
                    .padding(horizontal = 12.dp, vertical = 72.dp)
            )
        }

        if (uiState.offlineState.isOfflineActive && !isProfileMenuOpen) {
            OfflineStatusBadge(
                offlineState = uiState.offlineState,
                modifier = Modifier
                    .align(Alignment.TopCenter)
                    .padding(top = 10.dp)
            )
        }

        if (isFullPlayerOpen && displayedPlayback.currentTrack != null) {
            FullPlayerOverlay(
                playback = displayedPlayback,
                coverBitmap = mediaImageFor(uiState.mediaImages, displayedPlayback.currentTrack?.coverUrl),
                mediaImages = uiState.mediaImages,
                likedTrackIds = uiState.likedTrackIds,
                onMediaImageNeeded = viewModel::loadMediaImage,
                dragOffsetY = fullPlayerDragOffset,
                onDragOffsetChange = { fullPlayerDragOffset = it },
                onDismiss = {
                    isFullPlayerOpen = false
                    fullPlayerDragOffset = 0f
                },
                onPlayPause = viewModel::togglePlayPause,
                onPrevious = viewModel::previousTrack,
                onNext = viewModel::nextTrack,
                onToggleShuffle = viewModel::toggleShuffle,
                onCycleRepeatMode = viewModel::cycleRepeatMode,
                onSeekToProgress = viewModel::seekToPlaybackProgress,
                onQueueTrackClick = { track, index ->
                    viewModel.playTrack(track, displayedPlayback.queue, index)
                },
                onToggleLike = viewModel::toggleLike,
                onPlayNext = viewModel::addToPlayNext,
                onPlayLast = viewModel::addToQueueEnd,
                onShare = viewModel::shareTrack,
                onAddToPlaylist = { track -> addToPlaylistTrack = track },
                onArtistClick = { artist ->
                    isFullPlayerOpen = false
                    viewModel.openArtist(artist)
                },
                connectedDevicesState = uiState.connectedDevicesState,
                connectedDevicesError = uiState.connectedDevicesError,
                onDeviceClick = viewModel::setActiveDevice,
                onCreateJam = viewModel::createJam,
                onJoinJam = viewModel::joinJam,
                onLeaveJam = viewModel::leaveJam,
                jamInviteQuery = uiState.jamInviteQuery,
                jamInviteUsers = uiState.jamInviteUsers,
                isJamInviteSearchLoading = uiState.isJamInviteSearchLoading,
                onJamInviteQueryChange = viewModel::onJamInviteQueryChange,
                onInviteToJam = viewModel::inviteToJam
            )
        }

        if (uiState.isListeningHistoryVisible) {
            ListeningHistoryPanel(
                uiState = uiState,
                onDismiss = viewModel::closeListeningHistory,
                onRetry = viewModel::retryListeningHistory
            )
        }

        addToPlaylistTrack?.let { track ->
            AddToPlaylistDialog(
                playlists = uiState.playlists,
                isLoading = uiState.isPlaylistsLoading,
                onLoadPlaylists = viewModel::loadPlaylists,
                onCreatePlaylist = {
                    addToPlaylistTrack = null
                    openCreatePlaylistDialog(track)
                },
                onPlaylistSelected = { playlistId ->
                    viewModel.addTrackToPlaylist(track.id, playlistId)
                    addToPlaylistTrack = null
                },
                onDismiss = { addToPlaylistTrack = null }
            )
        }

        if (isCreatePlaylistDialogOpen) {
            CreatePlaylistDialog(
                isCreating = uiState.isCreatingPlaylist,
                errorMessage = uiState.playlistCreateError,
                onSubmit = { title ->
                    viewModel.createPlaylist(
                        title = title,
                        trackIdToAdd = createPlaylistTrack?.id
                    ) {
                        isCreatePlaylistDialogOpen = false
                        createPlaylistTrack = null
                    }
                },
                onDismiss = {
                    if (!uiState.isCreatingPlaylist) {
                        isCreatePlaylistDialogOpen = false
                        createPlaylistTrack = null
                    }
                }
            )
        }

        deletePlaylistCandidate?.let { playlist ->
            DeletePlaylistDialog(
                playlist = playlist,
                isDeleting = uiState.isDeletingPlaylist,
                errorMessage = uiState.playlistDeleteError,
                onConfirm = {
                    viewModel.deletePlaylist(playlist) {
                        deletePlaylistCandidate = null
                    }
                },
                onDismiss = {
                    if (!uiState.isDeletingPlaylist) {
                        deletePlaylistCandidate = null
                    }
                }
            )
        }
    }
}

private fun PlayerUiState.displayedPlayback(): AudioPlaybackState {
    if (offlineState.isOfflineActive) return playback
    val connectedState = connectedDevicesState
    val remotePlayback = connectedState?.remotePlaybackState
    return if (connectedState != null &&
        (!connectedState.isCurrentDeviceActive || connectedState.isControllingRemoteJam()) &&
        remotePlayback != null
    ) {
        remotePlayback.toAudioPlaybackState()
    } else {
        playback
    }
}

private fun ConnectedDevicesState.isControllingRemoteJam(): Boolean {
    val currentJam = jams.firstOrNull { it.id == currentJamId }
        ?: jams.firstOrNull { it.isActive }
    return currentJam != null && currentJam.isMember && !currentJam.isOwner
}

private fun ConnectedPlaybackState.toAudioPlaybackState(): AudioPlaybackState {
    return AudioPlaybackState(
        queue = tracks,
        currentIndex = index,
        isPlaying = !paused,
        isBuffering = false,
        positionMs = (positionSeconds * 1_000.0).toLong().coerceAtLeast(0L),
        durationMs = (durationSeconds * 1_000.0).toLong().coerceAtLeast(0L),
        shuffle = shuffle,
        repeatMode = repeatMode,
        volume = volume.toFloat()
    )
}
