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.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
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.OutlinedTextField
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.text.input.ImeAction
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 TrackContextMenu(
    expanded: Boolean,
    isLiked: Boolean,
    onDismiss: () -> Unit,
    onToggleLike: () -> Unit,
    onPlayNext: () -> Unit,
    onPlayLast: () -> Unit,
    onShare: () -> Unit,
    onAddToPlaylist: () -> Unit
) {
    DropdownMenu(
        expanded = expanded,
        onDismissRequest = onDismiss
    ) {
        DropdownMenuItem(
            text = { Text(if (isLiked) "Unlike" else "Like") },
            onClick = onToggleLike
        )
        DropdownMenuItem(
            text = { Text("Play next") },
            onClick = onPlayNext
        )
        DropdownMenuItem(
            text = { Text("Play last") },
            onClick = onPlayLast
        )
        DropdownMenuItem(
            text = { Text("Share") },
            onClick = onShare
        )
        DropdownMenuItem(
            text = { Text("Add to playlist") },
            onClick = onAddToPlaylist
        )
    }
}

@Composable
internal fun AddToPlaylistDialog(
    playlists: List<PlaylistCard>,
    isLoading: Boolean,
    onLoadPlaylists: () -> Unit,
    onCreatePlaylist: () -> Unit,
    onPlaylistSelected: (Long) -> Unit,
    onDismiss: () -> Unit
) {
    LaunchedEffect(Unit) {
        onLoadPlaylists()
    }

    Surface(
        modifier = Modifier
            .fillMaxSize()
            .clickable(onClick = onDismiss),
        color = Color.Black.copy(alpha = 0.6f)
    ) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            Surface(
                modifier = Modifier
                    .width(300.dp)
                    .clickable(enabled = false, onClick = {}),
                shape = RoundedCornerShape(16.dp),
                color = FurumiSurfaceHigh,
                border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine)
            ) {
                Column(modifier = Modifier.padding(20.dp)) {
                    Text(
                        text = "Add to playlist",
                        style = MaterialTheme.typography.titleMedium,
                        color = MaterialTheme.colorScheme.onBackground
                    )
                    Spacer(modifier = Modifier.height(16.dp))

                    Surface(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clip(RoundedCornerShape(8.dp))
                            .clickable(onClick = onCreatePlaylist),
                        shape = RoundedCornerShape(8.dp),
                        color = FurumiNeonPink,
                    ) {
                        Row(
                            modifier = Modifier.padding(horizontal = 12.dp, vertical = 12.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            PlusGlyph(Modifier.size(18.dp), FurumiBlack)
                            Spacer(modifier = Modifier.width(10.dp))
                            Text(
                                text = "Create new playlist",
                                style = MaterialTheme.typography.labelLarge,
                                color = FurumiBlack
                            )
                        }
                    }

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

                    when {
                        isLoading -> {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(100.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                CircularProgressIndicator(
                                    color = FurumiNeonPink,
                                    strokeWidth = 2.dp,
                                    modifier = Modifier.size(24.dp)
                                )
                            }
                        }
                        playlists.isEmpty() -> {
                            Text(
                                text = "No playlists found",
                                style = MaterialTheme.typography.bodyMedium,
                                color = FurumiTextMuted
                            )
                        }
                        else -> {
                            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                                playlists.forEach { playlist ->
                                    Surface(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .clip(RoundedCornerShape(8.dp))
                                            .clickable { onPlaylistSelected(playlist.id) },
                                        shape = RoundedCornerShape(8.dp),
                                        color = FurumiSurface,
                                        border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine)
                                    ) {
                                        Column(modifier = Modifier.padding(12.dp)) {
                                            Text(
                                                text = playlist.title,
                                                style = MaterialTheme.typography.labelLarge,
                                                color = MaterialTheme.colorScheme.onBackground,
                                                maxLines = 1,
                                                overflow = TextOverflow.Ellipsis
                                            )
                                            Text(
                                                text = "${playlist.trackCount} tracks",
                                                style = MaterialTheme.typography.bodyMedium,
                                                color = FurumiTextMuted
                                            )
                                        }
                                    }
                                }
                            }
                        }
                    }

                    Spacer(modifier = Modifier.height(16.dp))
                    Text(
                        text = "Cancel",
                        modifier = Modifier
                            .align(Alignment.End)
                            .clip(RoundedCornerShape(8.dp))
                            .clickable(onClick = onDismiss)
                            .padding(horizontal = 10.dp, vertical = 8.dp),
                        style = MaterialTheme.typography.labelLarge,
                        color = FurumiTextMuted
                    )
                }
            }
        }
    }
}

@Composable
internal fun CreatePlaylistDialog(
    isCreating: Boolean,
    errorMessage: String?,
    onSubmit: (String) -> Unit,
    onDismiss: () -> Unit
) {
    var title by rememberSaveable { mutableStateOf("") }
    val trimmedTitle = title.trim()
    val canSubmit = trimmedTitle.isNotBlank() && !isCreating
    val submit = {
        if (canSubmit) {
            onSubmit(trimmedTitle)
        }
    }

    Surface(
        modifier = Modifier
            .fillMaxSize()
            .clickable(enabled = !isCreating, onClick = onDismiss),
        color = Color.Black.copy(alpha = 0.6f)
    ) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            Surface(
                modifier = Modifier
                    .width(320.dp)
                    .clickable(enabled = false, onClick = {}),
                shape = RoundedCornerShape(16.dp),
                color = FurumiSurfaceHigh,
                border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine)
            ) {
                Column(modifier = Modifier.padding(20.dp)) {
                    Text(
                        text = "Create playlist",
                        style = MaterialTheme.typography.titleMedium,
                        color = MaterialTheme.colorScheme.onBackground
                    )
                    Spacer(modifier = Modifier.height(14.dp))
                    OutlinedTextField(
                        value = title,
                        onValueChange = { title = it },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        enabled = !isCreating,
                        label = { Text("Name") },
                        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
                        keyboardActions = KeyboardActions(onDone = { submit() })
                    )
                    errorMessage?.let { message ->
                        Spacer(modifier = Modifier.height(10.dp))
                        Text(
                            text = message,
                            style = MaterialTheme.typography.bodyMedium,
                            color = FurumiHotOrange
                        )
                    }
                    Spacer(modifier = Modifier.height(18.dp))
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        OutlinedButton(
                            onClick = onDismiss,
                            enabled = !isCreating,
                            shape = CircleShape,
                            border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine),
                            colors = ButtonDefaults.outlinedButtonColors(
                                contentColor = MaterialTheme.colorScheme.onBackground,
                                disabledContentColor = FurumiTextMuted
                            )
                        ) {
                            Text("Cancel")
                        }
                        Button(
                            onClick = submit,
                            enabled = canSubmit,
                            shape = CircleShape,
                            colors = ButtonDefaults.buttonColors(
                                containerColor = FurumiNeonPink,
                                contentColor = FurumiBlack,
                                disabledContainerColor = FurumiSurface,
                                disabledContentColor = FurumiTextMuted
                            )
                        ) {
                            if (isCreating) {
                                CircularProgressIndicator(
                                    color = FurumiBlack,
                                    strokeWidth = 2.dp,
                                    modifier = Modifier.size(18.dp)
                                )
                            } else {
                                Text("Create")
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
internal fun DeletePlaylistDialog(
    playlist: PlaylistCard,
    isDeleting: Boolean,
    errorMessage: String?,
    onConfirm: () -> Unit,
    onDismiss: () -> Unit
) {
    Surface(
        modifier = Modifier
            .fillMaxSize()
            .clickable(enabled = !isDeleting, onClick = onDismiss),
        color = Color.Black.copy(alpha = 0.6f)
    ) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            Surface(
                modifier = Modifier
                    .width(320.dp)
                    .clickable(enabled = false, onClick = {}),
                shape = RoundedCornerShape(16.dp),
                color = FurumiSurfaceHigh,
                border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine)
            ) {
                Column(modifier = Modifier.padding(20.dp)) {
                    Text(
                        text = "Delete playlist?",
                        style = MaterialTheme.typography.titleMedium,
                        color = MaterialTheme.colorScheme.onBackground
                    )
                    Spacer(modifier = Modifier.height(10.dp))
                    Text(
                        text = playlist.title,
                        style = MaterialTheme.typography.labelLarge,
                        color = MaterialTheme.colorScheme.onBackground,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = "This cannot be undone.",
                        style = MaterialTheme.typography.bodyMedium,
                        color = FurumiTextMuted
                    )
                    errorMessage?.let { message ->
                        Spacer(modifier = Modifier.height(10.dp))
                        Text(
                            text = message,
                            style = MaterialTheme.typography.bodyMedium,
                            color = FurumiHotOrange
                        )
                    }
                    Spacer(modifier = Modifier.height(18.dp))
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        OutlinedButton(
                            onClick = onDismiss,
                            enabled = !isDeleting,
                            shape = CircleShape,
                            border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine),
                            colors = ButtonDefaults.outlinedButtonColors(
                                contentColor = MaterialTheme.colorScheme.onBackground,
                                disabledContentColor = FurumiTextMuted
                            )
                        ) {
                            Text("Cancel")
                        }
                        Button(
                            onClick = onConfirm,
                            enabled = !isDeleting,
                            shape = CircleShape,
                            colors = ButtonDefaults.buttonColors(
                                containerColor = FurumiHotOrange,
                                contentColor = FurumiBlack,
                                disabledContainerColor = FurumiSurface,
                                disabledContentColor = FurumiTextMuted
                            )
                        ) {
                            if (isDeleting) {
                                CircularProgressIndicator(
                                    color = FurumiBlack,
                                    strokeWidth = 2.dp,
                                    modifier = Modifier.size(18.dp)
                                )
                            } else {
                                Text("Delete")
                            }
                        }
                    }
                }
            }
        }
    }
}
