package com.horrortv.app.presentation.common

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import coil.size.Size
import android.graphics.Bitmap
import com.horrortv.app.R
import com.horrortv.app.presentation.theme.HorrorColors
import com.horrortv.app.util.PosterSize
import com.horrortv.app.util.PosterUtils

@Composable
fun PosterImage(
    url: String?,
    contentDescription: String?,
    modifier: Modifier = Modifier,
    size: Int = PosterSize.CARD,
    contentScale: ContentScale = ContentScale.Crop,
    shape: Shape? = null
) {
    val context = LocalContext.current
    val optimizedUrl = remember(url, size) {
        PosterUtils.optimizePosterUrl(url, size)
    }

    val request = remember(optimizedUrl) {
        ImageRequest.Builder(context)
            .data(optimizedUrl)
            .memoryCacheKey(optimizedUrl)
            .diskCacheKey(optimizedUrl)
            .placeholder(R.drawable.poster_placeholder)
            .error(R.drawable.poster_error)
            .size(Size(size, size))
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build()
    }

    Box(
        modifier = modifier
            .then(if (shape != null) Modifier.clip(shape) else Modifier)
            .background(HorrorColors.HorrorGray),
        contentAlignment = Alignment.Center
    ) {
        AsyncImage(
            model = request,
            contentDescription = contentDescription,
            contentScale = contentScale,
            modifier = Modifier.fillMaxSize()
        )
    }
}

@Composable
fun BackgroundPosterImage(
    url: String?,
    modifier: Modifier = Modifier
) {
    PosterImage(
        url = url,
        contentDescription = null,
        modifier = modifier,
        size = PosterSize.BACKGROUND,
        contentScale = ContentScale.Crop
    )
}