package com.tt.honeyDue.ui.components

import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.BrokenImage
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import coil3.compose.SubcomposeAsyncImage
import coil3.compose.SubcomposeAsyncImageContent
import coil3.compose.AsyncImagePainter
import coil3.compose.LocalPlatformContext
import coil3.request.ImageRequest
import coil3.network.NetworkHeaders
import coil3.network.httpHeaders
import com.tt.honeyDue.network.ApiClient
import com.tt.honeyDue.storage.TokenStorage

/**
 * A Compose component that loads images from authenticated API endpoints.
 * Use this for media that requires auth token (documents, completions, etc.)
 *
 * Example usage:
 * ```kotlin
 * AuthenticatedImage(
 *     mediaUrl = document.mediaUrl,
 *     contentDescription = "Document image"
 * )
 * ```
 */
@Composable
fun AuthenticatedImage(
    mediaUrl: String?,
    modifier: Modifier = Modifier,
    contentDescription: String? = null,
    contentScale: ContentScale = ContentScale.Fit,
    placeholder: @Composable () -> Unit = { DefaultPlaceholder() },
    errorContent: @Composable () -> Unit = { DefaultErrorContent() }
) {
    if (mediaUrl.isNullOrEmpty()) {
        Box(modifier = modifier, contentAlignment = Alignment.Center) {
            errorContent()
        }
        return
    }

    val baseUrl = ApiClient.getMediaBaseUrl()
    val token = TokenStorage.getToken()
    val fullUrl = baseUrl + mediaUrl
    val context = LocalPlatformContext.current

    val imageRequest = remember(fullUrl, token) {
        ImageRequest.Builder(context)
            .data(fullUrl)
            .apply {
                if (token != null) {
                    httpHeaders(
                        NetworkHeaders.Builder()
                            .set("Authorization", "Token $token")
                            .build()
                    )
                }
            }
            .build()
    }

    SubcomposeAsyncImage(
        model = imageRequest,
        contentDescription = contentDescription,
        modifier = modifier,
        contentScale = contentScale
    ) {
        when (painter.state) {
            is AsyncImagePainter.State.Loading -> {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    placeholder()
                }
            }
            is AsyncImagePainter.State.Error -> {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    errorContent()
                }
            }
            else -> SubcomposeAsyncImageContent()
        }
    }
}

@Composable
private fun DefaultPlaceholder() {
    CircularProgressIndicator(
        modifier = Modifier.size(32.dp),
        color = MaterialTheme.colorScheme.primary
    )
}

@Composable
private fun DefaultErrorContent() {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Icon(
            Icons.Default.BrokenImage,
            contentDescription = "Failed to load",
            modifier = Modifier.size(40.dp),
            tint = MaterialTheme.colorScheme.onSurfaceVariant
        )
        Spacer(modifier = Modifier.height(4.dp))
        Text(
            "Failed to load",
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}
