package dev.meloda.fast.messageshistory.presentation

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.Crossfade
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import androidx.core.view.HapticFeedbackConstantsCompat
import coil.compose.AsyncImage
import dev.chrisbanes.haze.HazeState
import dev.chrisbanes.haze.hazeEffect
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
import dev.chrisbanes.haze.materials.HazeMaterials
import dev.meloda.fast.datastore.AppSettings
import dev.meloda.fast.ui.R
import dev.meloda.fast.ui.theme.LocalThemeConfig

@OptIn(ExperimentalMaterial3Api::class, ExperimentalHazeMaterialsApi::class)
@Composable
fun MessagesHistoryTopBar(
    modifier: Modifier = Modifier,
    hazeState: HazeState,
    showReplyAction: Boolean,
    showEditAction: Boolean,
    isClickable: Boolean,
    isMessagesSelecting: Boolean,
    isPeerAccount: Boolean,
    avatarUrl: String?,
    avatarResourceId: Int?,
    title: String,
    isEditing: Boolean,
    onTopBarClicked: () -> Unit = {},
    onBack: () -> Unit = {},
    onClose: () -> Unit = {},
    onDeleteSelectedButtonClicked: () -> Unit = {},
    onRefresh: () -> Unit = {},
    onEditSelectedMessageClicked: () -> Unit = {}
) {
    val view = LocalView.current
    val theme = LocalThemeConfig.current

    var dropDownMenuExpanded by remember {
        mutableStateOf(false)
    }

    TopAppBar(
        modifier = modifier
            .then(
                if (theme.enableBlur) {
                    Modifier.hazeEffect(
                        state = hazeState,
                        style = HazeMaterials.thick()
                    )
                } else Modifier
            )
            .fillMaxWidth()
            .then(
                if (!isClickable) Modifier
                else Modifier.clickable {
                    onTopBarClicked()
                }
            ),
        title = {
            Row(
//                modifier = Modifier.weight(1f),
                verticalAlignment = Alignment.CenterVertically
            ) {
                AnimatedVisibility(!isMessagesSelecting && !isEditing) {
                    Row {
                        if (isPeerAccount) {
                            Box(
                                modifier = Modifier
                                    .size(36.dp)
                                    .clip(CircleShape)
                                    .background(MaterialTheme.colorScheme.primary)
                            ) {
                                Icon(
                                    modifier = Modifier
                                        .align(Alignment.Center)
                                        .size(24.dp),
                                    painter = painterResource(id = R.drawable.ic_bookmark_round_24),
                                    contentDescription = "Favorites icon",
                                    tint = MaterialTheme.colorScheme.onPrimary
                                )
                            }
                        } else {
                            when {
                                avatarUrl != null -> {
                                    AsyncImage(
                                        model = avatarUrl,
                                        contentDescription = "Profile Image",
                                        modifier = Modifier
                                            .size(36.dp)
                                            .clip(CircleShape),
                                        placeholder = painterResource(id = R.drawable.ic_account_circle_fill_round_24),
                                    )
                                }

                                avatarResourceId != null -> {
                                    Image(
                                        painter = painterResource(avatarResourceId),
                                        contentDescription = null,
                                        modifier = Modifier
                                            .size(36.dp)
                                            .clip(CircleShape)
                                    )
                                }
                            }
                        }

                        Spacer(modifier = Modifier.width(12.dp))
                    }
                }

                Text(
                    modifier = Modifier.animateContentSize(),
                    text = title,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    style = MaterialTheme.typography.headlineSmall
                )
            }
        },
        navigationIcon = {
            IconButton(
                onClick = {
                    if (!isMessagesSelecting && !isEditing) onBack()
                    else onClose()
                }
            ) {
                Crossfade(targetState = !isMessagesSelecting && !isEditing) { state ->
                    Icon(
                        painter = painterResource(
                            if (state) {
                                R.drawable.ic_arrow_back_round_24
                            } else {
                                R.drawable.ic_close_round_24
                            }
                        ),
                        contentDescription = if (state) "Close button"
                        else "Back button"
                    )
                }
            }
        },
        colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent),
        actions = {
            if (isMessagesSelecting) {
                AnimatedVisibility(showReplyAction) {
                    IconButton(
                        onClick = {
                            if (AppSettings.General.enableHaptic) {
                                view.performHapticFeedback(HapticFeedbackConstantsCompat.REJECT)
                            }
                        }
                    ) {
                        Icon(
                            painter = painterResource(R.drawable.ic_reply_round_24),
                            contentDescription = null
                        )
                    }
                }
                IconButton(
                    onClick = {
                        if (AppSettings.General.enableHaptic) {
                            view.performHapticFeedback(HapticFeedbackConstantsCompat.REJECT)
                        }
                    }
                ) {
                    Icon(
                        painter = painterResource(R.drawable.ic_reply_all_round_24),
                        contentDescription = null
                    )
                }
                IconButton(
                    onClick = {
                        if (AppSettings.General.enableHaptic) {
                            view.performHapticFeedback(HapticFeedbackConstantsCompat.REJECT)
                        }
                    }
                ) {
                    Icon(
                        painter = painterResource(R.drawable.ic_forward_round_24),
                        contentDescription = null
                    )
                }

                AnimatedVisibility(showEditAction) {
                    IconButton(onClick = onEditSelectedMessageClicked) {
                        Icon(
                            painter = painterResource(R.drawable.ic_edit_round_24),
                            contentDescription = null
                        )
                    }
                }

                IconButton(onClick = onDeleteSelectedButtonClicked) {
                    Icon(
                        painter = painterResource(R.drawable.ic_delete_round_24),
                        contentDescription = null
                    )
                }
            } else {
                val dropDownItems = mutableListOf<@Composable () -> Unit>()

                if (AppSettings.General.showManualRefreshOptions) {
                    dropDownItems += {
                        DropdownMenuItem(
                            onClick = {
                                onRefresh()
                                dropDownMenuExpanded = false
                            },
                            text = {
                                Text(text = stringResource(R.string.action_refresh))
                            },
                            leadingIcon = {
                                Icon(
                                    painter = painterResource(R.drawable.ic_refresh_round_24),
                                    contentDescription = null
                                )
                            }
                        )
                    }
                }

                if (dropDownItems.isNotEmpty()) {
                    IconButton(
                        onClick = { dropDownMenuExpanded = true }
                    ) {
                        Icon(
                            painter = painterResource(R.drawable.ic_more_vert_round_24),
                            contentDescription = "Options"
                        )
                    }
                }

                DropdownMenu(
                    modifier = Modifier.defaultMinSize(minWidth = 140.dp),
                    expanded = dropDownMenuExpanded,
                    onDismissRequest = {
                        dropDownMenuExpanded = false
                    },
                    offset = DpOffset(x = (-4).dp, y = (-60).dp)
                ) {
                    dropDownItems.forEach { it.invoke() }
                }
            }
        }
    )
}
