package com.isidroid.c23.ui.screen.render_preview._component

import android.util.SparseArray
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.isidroid.rendering.model.RenderResult
import com.isidroid.c23.ui.screen.render_preview.RenderContract
import com.isidroid.render_preview.RenderPlaceholderComponent
import com.isidroid.render_preview.RenderPreviewComponent
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.distinctUntilChanged

@Composable
fun PagerPreviewComponent(
    state: State<RenderContract.State>,
    renderResultsFlow: StateFlow<SparseArray<RenderResult>?>?,
    modifier: Modifier,
    onPageOpened: (page: Int, containerSize: IntSize?) -> Unit,
) {
    var containerSize by remember { mutableStateOf<IntSize?>(null) }

    if (containerSize == null)
        RenderPlaceholderComponent(
            onSize = { containerSize = it },
            modifier = modifier.fillMaxSize()
        )
    else
        PagerContent(
            state = state,
            renderResultsFlow = renderResultsFlow,
            modifier = modifier,
            onPageOpened = { onPageOpened(it, containerSize) }
        )
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun PagerContent(
    state: State<RenderContract.State>,
    renderResultsFlow: StateFlow<SparseArray<RenderResult>?>?,
    modifier: Modifier,
    onPageOpened: (Int) -> Unit,
) {
    val pageCount = state.value.pageCount
    val renderResults = renderResultsFlow?.collectAsState(initial = null)
    var currentPage by remember { mutableIntStateOf(1) }

    val pagerState = rememberPagerState(
        pageCount = { pageCount },
    )

    LaunchedEffect(pagerState) {
        snapshotFlow { pagerState.currentPage }
            .distinctUntilChanged()
            .collect { page ->
                currentPage = page + 1
                onPageOpened(page)
            }
    }

    Column(
        modifier = modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {

        HorizontalPager(
            state = pagerState,
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
        ) {
            val currentRender = renderResults?.value?.get(it)

            if (currentRender != null) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier.fillMaxSize()
                ) {
                    RenderPreviewComponent(
                        widthPx = currentRender.width,
                        heightPx = currentRender.height,
                        filePath = currentRender.filePath,
                        modifier = Modifier
                    )
                }


            } else {
                Column(
                    Modifier.fillMaxSize(),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {

                    Text(text = "Loading")
                }
            }
        }

        PagerIndicatorComponent(
            currentPage = currentPage,
            totalPage = pageCount,
            modifier = Modifier.padding(top = 6.dp)
        )
    }
}


@Composable
private fun PagerIndicatorComponent(
    currentPage: Int,
    totalPage: Int,
    modifier: Modifier = Modifier
) {
    Text(
        text = "Page $currentPage of $totalPage",
        color = Color.White,
        fontSize = 16.sp,
        fontWeight = FontWeight.Light,
        letterSpacing = .48.sp,
        modifier = modifier
            .background(Color.Black.copy(alpha = .45f), RoundedCornerShape(24.dp))
            .padding(horizontal = 24.dp, vertical = 12.dp)
    )
}