package moe.lava.neon.ui.util

import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.MaterialExpressiveTheme
import androidx.compose.material3.MotionScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.graphics.painter.Painter
import coil3.ColorImage
import coil3.annotation.ExperimentalCoilApi
import coil3.compose.AsyncImagePainter
import coil3.compose.AsyncImagePreviewHandler
import coil3.compose.LocalAsyncImagePreviewHandler
import coil3.request.SuccessResult
import moe.lava.neon.resources.Res
import moe.lava.neon.resources.placeholder_1
import moe.lava.neon.resources.placeholder_10
import moe.lava.neon.resources.placeholder_11
import moe.lava.neon.resources.placeholder_2
import moe.lava.neon.resources.placeholder_3
import moe.lava.neon.resources.placeholder_4
import moe.lava.neon.resources.placeholder_5
import moe.lava.neon.resources.placeholder_6
import moe.lava.neon.resources.placeholder_7
import moe.lava.neon.resources.placeholder_8
import moe.lava.neon.resources.placeholder_9
import org.jetbrains.compose.resources.painterResource

@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalCoilApi::class)
@Composable
fun ThemedPreview(content: @Composable () -> Unit) {
    val placeholders = placeholders()
    val previewHandler = AsyncImagePreviewHandler { _, request ->
        val img = ColorImage(0)
        AsyncImagePainter.State.Success(placeholders.next(), SuccessResult(img, request))
    }
    CompositionLocalProvider(LocalAsyncImagePreviewHandler provides previewHandler) {
        MaterialExpressiveTheme(
            // This will break live previews
            // colorScheme = getColorScheme(),
            motionScheme = MotionScheme.Companion.expressive(),
        ) {
            content()
        }
    }
}

@Composable
private fun placeholders(): Iterator<Painter> {
    val list = listOf(
        Res.drawable.placeholder_1,
        Res.drawable.placeholder_2,
        Res.drawable.placeholder_3,
        Res.drawable.placeholder_4,
        Res.drawable.placeholder_5,
        Res.drawable.placeholder_6,
        Res.drawable.placeholder_7,
        Res.drawable.placeholder_8,
        Res.drawable.placeholder_9,
        Res.drawable.placeholder_10,
        Res.drawable.placeholder_11,
    ).map { painterResource(it) }
    return object : Iterator<Painter> {
        override fun hasNext() = true

        private var idx = 0
        private val maxIdx = list.size
        override fun next(): Painter {
            if (idx >= maxIdx) idx = 0
            return list[idx++]
        }
    }
}

