package net.buzzert.kordophonedroid.ui.attachments

import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import coil.compose.SubcomposeAsyncImage
import coil.request.ImageRequest
import net.buzzert.kordophonedroid.ui.LocalNavController
import net.buzzert.kordophonedroid.ui.theme.KordophoneTopAppBar
import net.engawapg.lib.zoomable.rememberZoomState
import net.engawapg.lib.zoomable.zoomable

@Composable
fun AttachmentViewer(attachmentGuid: String) {
    var topBarVisible = remember { mutableStateOf(true) }
    val navController = LocalNavController.current
    Scaffold(topBar = {
        KordophoneTopAppBar(
            title = "Attachment",
            backAction = { navController.popBackStack() },
            visible = topBarVisible.value
        )
    }) { padding ->
        val zoomState = rememberZoomState()
        val interactionSource = remember { MutableInteractionSource() }
        val data = AttachmentFetchData(attachmentGuid, preview = false)
        Column(modifier = Modifier.padding(padding)) {
            Spacer(modifier = Modifier.weight(1f))

            SubcomposeAsyncImage(
                model = ImageRequest.Builder(LocalContext.current)
                    .data(data)
                    .crossfade(true)
                    .build(),
                contentDescription = "",
                loading = {
                    Box {
                        CircularProgressIndicator(
                            modifier = Modifier.align(Alignment.Center)
                        )
                    }
                },
                modifier = Modifier
                    .zoomable(zoomState)
                    .fillMaxWidth()
                    .align(Alignment.CenterHorizontally)
                    .clickable(
                        interactionSource = interactionSource,
                        indication = null
                    ) {
                        topBarVisible.value = !topBarVisible.value
                    }
            )

            Spacer(modifier = Modifier.weight(1f))
        }
    }
}