package com.seven.ikar.kotlin.ui

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.compositionLocalOf
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.layout.ContentScale
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.seven.ikar.kotlin.core.network.ServerConfig

val LocalIkarAccessToken = compositionLocalOf<String?> { null }

@Composable
fun AvatarView(
    imageUrl: String?,
    title: String,
    accessToken: String? = null,
    size: Dp = 44.dp
) {
    val resolvedImageUrl = ServerConfig.normalizeMediaUrl(imageUrl)
    val resolvedAccessToken = accessToken ?: LocalIkarAccessToken.current
    val avatarColor = ikarAvatarColor(title)
    val initials = ikarAvatarInitials(title)
    val fontSize = when {
        size >= 96.dp -> 32.dp
        size >= 72.dp -> 24.dp
        size >= 54.dp -> 18.dp
        else -> 16.dp
    }

    Box(
        modifier = Modifier
            .size(size)
            .clip(CircleShape)
            .background(avatarColor),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = initials,
            style = MaterialTheme.typography.titleLarge.copy(
                fontSize = fontSize.value.sp,
                color = Color.White
            ),
            textAlign = TextAlign.Center
        )

        AuthenticatedAsyncImage(
            imageUrl = resolvedImageUrl,
            accessToken = resolvedAccessToken,
            contentDescription = title,
            modifier = Modifier.matchParentSize(),
            contentScale = ContentScale.Crop
        )
    }
}
