package com.aiosman.ravenow.ui.composables

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.res.painterResource
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import kotlinx.coroutines.launch

@Composable
fun AnimatedFavouriteIcon(
    modifier: Modifier = Modifier,
    isFavourite: Boolean = false,
    onClick: (() -> Unit)? = null
) {
    val AppColors = LocalAppTheme.current
    val animatableRotation = remember { Animatable(0f) }
    val scope = rememberCoroutineScope()
    suspend fun shake() {
        repeat(2) {
            animatableRotation.animateTo(
                targetValue = 10f,
                animationSpec = tween(100)
            ) {

            }
            animatableRotation.animateTo(
                targetValue = -10f,
                animationSpec = tween(100)
            ) {

            }

        }
        animatableRotation.animateTo(
            targetValue = 0f,
            animationSpec = tween(100)
        )
    }
    Box(contentAlignment = Alignment.Center, modifier = Modifier.noRippleClickable {
        onClick?.invoke()
        // Trigger shake animation
        scope.launch {
            shake()
        }
    }) {
        Image(
            painter =  if (isFavourite) {
                painterResource(id = R.drawable.rider_pro_favourited)
            } else {
                painterResource(id = R.drawable.rider_pro_favourite)
            },
            contentDescription = "Favourite",
            modifier = modifier.graphicsLayer {
                rotationZ = animatableRotation.value
            },
            colorFilter = ColorFilter.tint(AppColors.text)
        )
    }
}