package com.atridad.ascently.ui.components

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
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.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import kotlinx.coroutines.launch

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun FullscreenImageViewer(imagePaths: List<String>, initialIndex: Int = 0, onDismiss: () -> Unit) {
    val pagerState = rememberPagerState(initialPage = initialIndex, pageCount = { imagePaths.size })
    val thumbnailListState = rememberLazyListState()
    val coroutineScope = rememberCoroutineScope()

    // Handle back button press
    BackHandler { onDismiss() }

    // Auto-scroll thumbnail list to center current image
    LaunchedEffect(pagerState.currentPage) {
        if (imagePaths.size > 1) {
            thumbnailListState.animateScrollToItem(
                index = pagerState.currentPage,
                scrollOffset = -200,
            )
        }
    }

    Dialog(
        onDismissRequest = onDismiss,
        properties =
        DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = true),
    ) {
        Box(modifier = Modifier.fillMaxSize().background(Color.Black).systemBarsPadding()) {
            // Main image pager
            HorizontalPager(state = pagerState, modifier = Modifier.fillMaxSize()) { page ->
                OrientationAwareImage(
                    imagePath = imagePaths[page],
                    contentDescription = "Full screen image",
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Fit,
                )
            }

            // Top bar with back button and counter
            Surface(
                modifier = Modifier.fillMaxWidth().align(Alignment.TopStart),
                color = Color.Black.copy(alpha = 0.6f),
            ) {
                Row(
                    modifier =
                    Modifier.fillMaxWidth().padding(horizontal = 4.dp, vertical = 8.dp),
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    // Back button
                    IconButton(onClick = onDismiss) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "Close",
                            tint = Color.White,
                        )
                    }

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

                    // Image counter
                    if (imagePaths.size > 1) {
                        Text(
                            text = "${pagerState.currentPage + 1} / ${imagePaths.size}",
                            color = Color.White,
                            style = MaterialTheme.typography.bodyMedium,
                        )
                    }

                    Spacer(modifier = Modifier.width(16.dp))
                }
            }

            // Thumbnail strip at bottom (if multiple images)
            if (imagePaths.size > 1) {
                Surface(
                    modifier = Modifier.fillMaxWidth().align(Alignment.BottomCenter),
                    color = Color.Black.copy(alpha = 0.6f),
                ) {
                    LazyRow(
                        state = thumbnailListState,
                        modifier = Modifier.padding(vertical = 12.dp),
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                        contentPadding = PaddingValues(horizontal = 16.dp),
                    ) {
                        itemsIndexed(imagePaths) { index, imagePath ->
                            val isSelected = index == pagerState.currentPage

                            Box(
                                modifier =
                                Modifier.size(48.dp)
                                    .clip(RoundedCornerShape(8.dp))
                                    .clickable {
                                        coroutineScope.launch {
                                            pagerState.animateScrollToPage(index)
                                        }
                                    },
                            ) {
                                OrientationAwareImage(
                                    imagePath = imagePath,
                                    contentDescription = "Thumbnail ${index + 1}",
                                    modifier = Modifier.fillMaxSize(),
                                    contentScale = ContentScale.Crop,
                                )

                                // Selection indicator
                                if (isSelected) {
                                    Box(
                                        modifier =
                                        Modifier.fillMaxSize()
                                            .background(
                                                Color.White.copy(alpha = 0.3f),
                                                RoundedCornerShape(8.dp),
                                            ),
                                    )
                                    Box(
                                        modifier =
                                        Modifier.fillMaxSize()
                                            .background(
                                                Color.Transparent,
                                                RoundedCornerShape(8.dp),
                                            )
                                            .clip(RoundedCornerShape(8.dp))
                                            .background(
                                                Color.White.copy(alpha = 0.2f),
                                            ),
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
