package com.example.what_the_fantasy.ui.screens

import android.content.Context
import android.content.Intent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
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.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.MailOutline
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
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.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.what_the_fantasy.R
import coil.compose.AsyncImage
import com.example.what_the_fantasy.data.model.Comment
import com.example.what_the_fantasy.data.services.IServices
import com.example.what_the_fantasy.ui.components.NavBar
import com.example.what_the_fantasy.ui.states.CurrentUserState
import com.example.what_the_fantasy.ui.theme.colorBackground
import com.example.what_the_fantasy.ui.theme.gradienBox
import com.example.what_the_fantasy.ui.theme.iconText
import com.example.what_the_fantasy.ui.theme.likeIcon
import com.example.what_the_fantasy.ui.theme.whiteBackcgroundText
import com.example.what_the_fantasy.ui.viewModels.CurrentUserViewModel

var isCommentVisible by mutableStateOf(false)

@Composable
fun QuotePage(
    quoteId : Int,
    service : IServices,
    navAccueil: () -> Unit,
    navFavorite:() -> Unit,
    navQuiz: () -> Unit,
    navProfil:() -> Unit,
    navSearch: () -> Unit,
    currentUserVM : CurrentUserViewModel,
    currentUserState : CurrentUserState,
    )
{
    // utiliser ViewModel
    val quote = service.getQuote(quoteId) ?: return
    val context = LocalContext.current
    val user = service.getUserById(currentUserState.id) ?: return
    val favorite by remember { mutableStateOf(service.isFavorite(id = quoteId, user = user)) }
    NavBar(onProfile = true,
        currentUserVM = currentUserVM,
        currentUserState = currentUserState,
        navControllerFavorite = navFavorite,
        navControllerAccueil = navAccueil,
        navControllerProfil = navProfil,
        navControllerQuiz = navQuiz,
        navControllerSearch = navSearch
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.background),
            contentAlignment = Alignment.Center
        ) {
            Column(modifier = Modifier
                .padding(15.dp)
                .background(
                    color = MaterialTheme.colorScheme.primary,
                    shape = RoundedCornerShape(15.dp)
                )
            ) {
                Row(modifier = Modifier.padding(15.dp)) {
                    ImageQuote(
                        imageUrl = quote.imgUrl
                    )
                    Column {

                        FunctionalIcon(
                            isFavorite = favorite,
                            userId = currentUserState.id,
                            id = quoteId,
                            context = context,
                            service = service
                        )
                        QuoteText(
                            text = '"' + quote.content + '"'
                        )
                    }
                }
                Column(modifier = Modifier
                    .padding(15.dp)
                    .fillMaxWidth()
                ) {
                    InfoQuoteText(
                        nameId = R.string.source,
                        text = quote.source
                    )
                    InfoQuoteText(
                        nameId = R.string.charac,
                        text = quote.character
                    )
                    Row(
                        modifier = Modifier
                            .padding(top = 10.dp)
                            .align(alignment = Alignment.End)
                    ) {
                        LikeInfo(
                            likes = quote.likes
                        )
                    }
                }
            }
        }
        AnimatedVisibility(
            visible = isCommentVisible,
            enter = expandVertically(
                expandFrom = Alignment.CenterVertically
            ) + fadeIn(
                initialAlpha = 0.3f
            ) + slideInVertically(
                initialOffsetY = { -40 }
            ),
            exit = slideOutVertically() + shrinkVertically() + fadeOut()
        ) {
            Box(modifier = Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.primary).fillMaxSize()){
                Column {
                    AddComment(currentUserState.id, service)
                    LstComment(service.getComment(quoteId))
                }
            }
        }
    }
}

// ------------------ Composants non partager de la page --------------------------------------

@Composable
fun QuoteText(text: String ){
    Text(
        text = text,
        modifier = Modifier.padding(start = 10.dp, top = 15.dp),
        fontWeight = FontWeight(1000),
        fontSize = 20.sp,
        color = MaterialTheme.colorScheme.onPrimary
    )
}

@Composable
fun ImageQuote(imageUrl : String){
    AsyncImage(
        model = imageUrl,
        contentDescription = stringResource(R.string.profilePict),
        modifier = Modifier
        .size(150.dp)
        .clip(RoundedCornerShape(15.dp))
    )
}

@Composable
fun FunctionalIcon(isFavorite: Boolean, userId : Int, id : Int, context : Context, service: IServices){
    Row(modifier = Modifier
        .fillMaxWidth()
    ) {
        IconButton(
            onClick = {

                val sendIntent = Intent().apply {
                    action = Intent.ACTION_SEND
                    // lien a changer quand le site sra deployer
                    putExtra(Intent.EXTRA_TEXT, "http://wfWebsite/quote/$id")
                    type = "text/plain"
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }

                val shareIntent = Intent.createChooser(sendIntent, null)
                shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

                context.startActivity(shareIntent)
            },
            modifier = Modifier.padding(start = 15.dp)
        ) {
            Icon(
                Icons.Default.Share,
                contentDescription = stringResource(R.string.share),
                tint = MaterialTheme.colorScheme.onPrimary,
            )
        }
        IconButton(
            onClick = {
                isCommentVisible = !isCommentVisible
            },
            modifier = Modifier.padding(start = 20.dp)
        ){
            Icon(
                Icons.Default.MailOutline,
                contentDescription = stringResource(R.string.comment),
                tint = MaterialTheme.colorScheme.onPrimary,
            )
        }

        if(isFavorite){
            IconButton(
                onClick = { service.SupFav(userId = userId, QuoteId = id)}, //sup fav
                modifier = Modifier.padding(start = 20.dp)
            ){
                Icon(
                    Icons.Default.Favorite,
                    contentDescription = stringResource(R.string.favorite),
                    tint = MaterialTheme.colorScheme.onPrimary,
                )
            }

        }
        else{
            IconButton(
                onClick = { service.AddFav(userId = userId, QuoteId = id)}, //add fav
                modifier = Modifier.padding(start = 50.dp)
            ){
                Icon(
                    Icons.Default.FavoriteBorder,
                    contentDescription = stringResource(R.string.favorite),
                    tint = MaterialTheme.colorScheme.onPrimary
                )
            }
        }
    }
}

@Composable
fun InfoQuoteText(nameId : Int, text : String){
    Column(modifier = Modifier.padding(bottom = 20.dp)){
        Text(
            text = stringResource(id = nameId),
            fontSize = 18.sp,
            fontWeight = FontWeight(500),
            color = MaterialTheme.colorScheme.onPrimary
        )

        Text(
            text = text,
            color = MaterialTheme.colorScheme.onBackground,
            fontSize = 16.sp,
            fontWeight = FontWeight(400),
            modifier = Modifier
                .background(
                    color = MaterialTheme.colorScheme.background,
                    shape = RoundedCornerShape(15.dp)
                )
                .padding(5.dp)
        )
    }
}

@Composable
fun LikeInfo(likes : Int){
        Text(
            text = likes.toString(),
            color = MaterialTheme.colorScheme.onPrimary
        )
        Icon(
            Icons.Default.Favorite,
            contentDescription = stringResource(R.string.favorite),
            tint = MaterialTheme.colorScheme.onPrimary,
        )
}

@Composable
fun AddComment(userId: Int, service: IServices) {
    var text by remember { mutableStateOf("") }

    Row(
        modifier = Modifier
            .padding(15.dp)
            .fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically
    ) {
        IconButton(
            onClick = { isCommentVisible = !isCommentVisible }
        ) {
            Icon(
                imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                    contentDescription = stringResource(R.string.send),
                tint = MaterialTheme.colorScheme.onPrimary
            )
        }
        TextField(
            value = text,
            onValueChange = { text = it },
            label = { Text(stringResource(R.string.comment)) },
            modifier = Modifier
                .weight(1f)
                .padding(horizontal = 8.dp),
            shape = RoundedCornerShape(20.dp),
            colors = TextFieldDefaults.colors(
                focusedContainerColor = MaterialTheme.colorScheme.onPrimary,
                unfocusedContainerColor = MaterialTheme.colorScheme.onPrimary,
                focusedIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent,
                focusedLabelColor = MaterialTheme.colorScheme.primary,
                unfocusedLabelColor = MaterialTheme.colorScheme.primary
            ),
            trailingIcon = {
                IconButton(
                    onClick = { isCommentVisible = !isCommentVisible }
                ) {
                    Icon(
                        imageVector = Icons.AutoMirrored.Filled.Send,
                        contentDescription = "Retour",
                        tint = MaterialTheme.colorScheme.primary
                    )
                }
            }
        )
    }
}
@Composable
fun LstComment(lst: List<Comment>) {
    LazyColumn(
        verticalArrangement = Arrangement.spacedBy(8.dp),
        modifier = Modifier.padding(10.dp)
    ) {
        items(lst) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(
                        color = MaterialTheme.colorScheme.onPrimary,
                        shape = RoundedCornerShape(15.dp)
                    )
                    .padding(12.dp)
            ) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    AsyncImage(
                        model = it.img,
                        contentDescription = stringResource(R.string.profilePict),
                        modifier = Modifier
                            .size(50.dp)
                            .clip(RoundedCornerShape(50))
                    )
                    Text(
                        text = "${it.user}  •  ${it.date}",
                        color = MaterialTheme.colorScheme.onBackground,
                        modifier = Modifier.padding(start = 12.dp),
                        fontWeight = FontWeight.Bold,
                        fontSize = 14.sp
                    )
                }
                Text(
                    text = it.content,
                    color = MaterialTheme.colorScheme.onBackground,
                    modifier = Modifier.padding(top = 10.dp, start = 8.dp, end = 8.dp),
                    fontSize = 14.sp
                )
            }
        }
    }
}
