package com.github.nullptroma.wallenc.ui.elements

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.github.nullptroma.wallenc.ui.R

private const val BackButtonAnimMillis = 200

private val backButtonEnter = fadeIn(tween(BackButtonAnimMillis)) +
    slideInVertically(
        animationSpec = tween(BackButtonAnimMillis),
        initialOffsetY = { fullHeight -> fullHeight / 2 },
    )

private val backButtonExit = fadeOut(tween(BackButtonAnimMillis)) +
    slideOutVertically(
        animationSpec = tween(BackButtonAnimMillis),
        targetOffsetY = { fullHeight -> -fullHeight / 2 },
    )

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FloatingBackButton(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Surface(
        onClick = onClick,
        modifier = modifier.size(44.dp),
        shape = CircleShape,
        color = MaterialTheme.colorScheme.surfaceContainerHigh,
        shadowElevation = 4.dp,
        tonalElevation = 2.dp,
        contentColor = MaterialTheme.colorScheme.onSurface,
    ) {
        Icon(
            imageVector = Icons.AutoMirrored.Rounded.ArrowBack,
            contentDescription = stringResource(R.string.nav_cd_back),
            modifier = Modifier.padding(10.dp),
        )
    }
}

@Composable
fun AnimatedFloatingBackButton(
    visible: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    AnimatedVisibility(
        visible = visible,
        modifier = modifier,
        enter = backButtonEnter,
        exit = backButtonExit,
    ) {
        FloatingBackButton(onClick = onClick)
    }
}
