package com.atridad.openclimb.ui.components

import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
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.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.atridad.openclimb.utils.ImageUtils
import java.io.File

@Composable
fun ImagePicker(
    imageUris: List<String>,
    onImagesChanged: (List<String>) -> Unit,
    modifier: Modifier = Modifier,
    maxImages: Int = 5
) {
    val context = LocalContext.current
    var tempImageUris by remember { mutableStateOf(imageUris) }
    
    // Image picker launcher
    val imagePickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetMultipleContents()
    ) { uris ->
        if (uris.isNotEmpty()) {
            val currentCount = tempImageUris.size
            val remainingSlots = maxImages - currentCount
            val urisToProcess = uris.take(remainingSlots)
            
            // Process each selected image
            val newImagePaths = mutableListOf<String>()
            urisToProcess.forEach { uri ->
                val imagePath = ImageUtils.saveImageFromUri(context, uri)
                if (imagePath != null) {
                    newImagePaths.add(imagePath)
                }
            }
            
            if (newImagePaths.isNotEmpty()) {
                val updatedUris = tempImageUris + newImagePaths
                tempImageUris = updatedUris
                onImagesChanged(updatedUris)
            }
        }
    }
    
    Column(modifier = modifier) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "Photos (${tempImageUris.size}/$maxImages)",
                style = MaterialTheme.typography.titleMedium
            )
            
            if (tempImageUris.size < maxImages) {
                TextButton(
                    onClick = { 
                        imagePickerLauncher.launch("image/*")
                    }
                ) {
                    Icon(Icons.Default.Add, contentDescription = null, modifier = Modifier.size(16.dp))
                    Spacer(modifier = Modifier.width(4.dp))
                    Text("Add Photos")
                }
            }
        }
        
        if (tempImageUris.isNotEmpty()) {
            Spacer(modifier = Modifier.height(8.dp))
            
            LazyRow(
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                items(tempImageUris) { imagePath ->
                    ImageItem(
                        imagePath = imagePath,
                        onRemove = {
                            val updatedUris = tempImageUris.filter { it != imagePath }
                            tempImageUris = updatedUris
                            onImagesChanged(updatedUris)
                            
                            // Delete the image file
                            ImageUtils.deleteImage(context, imagePath)
                        }
                    )
                }
            }
        } else {
            Spacer(modifier = Modifier.height(8.dp))
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(100.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f)
                )
            ) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Icon(
                            Icons.Default.Add,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Spacer(modifier = Modifier.height(4.dp))
                        Text(
                            text = "Add photos of this problem",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun ImageItem(
    imagePath: String,
    onRemove: () -> Unit,
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current
    val imageFile = ImageUtils.getImageFile(context, imagePath)
    
    Box(
        modifier = modifier.size(80.dp)
    ) {
        AsyncImage(
            model = imageFile,
            contentDescription = "Problem photo",
            modifier = Modifier
                .fillMaxSize()
                .clip(RoundedCornerShape(8.dp)),
            contentScale = ContentScale.Crop
        )
        
        IconButton(
            onClick = onRemove,
            modifier = Modifier
                .align(Alignment.TopEnd)
                .size(24.dp)
        ) {
            Card(
                shape = RoundedCornerShape(12.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.errorContainer
                )
            ) {
                Icon(
                    Icons.Default.Close,
                    contentDescription = "Remove photo",
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(2.dp),
                    tint = MaterialTheme.colorScheme.onErrorContainer
                )
            }
        }
    }
}
