package com.placeholder.sherpai2.ui.explore

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
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.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel

/**
 * CLEANED ExploreScreen - No gradient header banner
 *
 * Removed:
 * - Gradient header box (lines 46-75) that created banner effect
 * - "Explore" title (MainScreen shows it)
 *
 * Features:
 * - Rectangular album cards (compact)
 * - Stories section (recent highlights)
 * - Clickable navigation to AlbumViewScreen
 * - Beautiful gradients and icons
 * - Mobile-friendly scrolling
 */
@Composable
fun ExploreScreen(
    onAlbumClick: (albumType: String, albumId: String) -> Unit,
    viewModel: ExploreViewModel = hiltViewModel(),
    modifier: Modifier = Modifier
) {
    val uiState by viewModel.uiState.collectAsState()

    Box(modifier = modifier.fillMaxSize()) {
        when (val state = uiState) {
            is ExploreViewModel.ExploreUiState.Loading -> {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            }

            is ExploreViewModel.ExploreUiState.Success -> {
                if (state.smartAlbums.isEmpty()) {
                    EmptyExploreView()
                } else {
                    ExploreContent(
                        smartAlbums = state.smartAlbums,
                        onAlbumClick = onAlbumClick
                    )
                }
            }

            is ExploreViewModel.ExploreUiState.Error -> {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.spacedBy(12.dp),
                        modifier = Modifier.padding(32.dp)
                    ) {
                        Icon(
                            Icons.Default.Error,
                            contentDescription = null,
                            modifier = Modifier.size(64.dp),
                            tint = MaterialTheme.colorScheme.error
                        )
                        Text(
                            text = "Error Loading Albums",
                            style = MaterialTheme.typography.titleLarge,
                            fontWeight = FontWeight.Bold
                        )
                        Text(
                            text = state.message,
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            textAlign = androidx.compose.ui.text.style.TextAlign.Center
                        )
                    }
                }
            }
        }
    }
}

/**
 * Main content - scrollable album sections
 */
@Composable
private fun ExploreContent(
    smartAlbums: List<SmartAlbum>,
    onAlbumClick: (albumType: String, albumId: String) -> Unit
) {
    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        contentPadding = PaddingValues(vertical = 16.dp),
        verticalArrangement = Arrangement.spacedBy(24.dp)
    ) {
        // Stories Section (Recent Highlights)
        item {
            val storyAlbums = smartAlbums.filter { it.imageCount > 0 }.take(10)
            if (storyAlbums.isNotEmpty()) {
                StoriesSection(
                    albums = storyAlbums,
                    onAlbumClick = onAlbumClick
                )
            }
        }

        // Time-based Albums
        val timeAlbums = smartAlbums.filterIsInstance<SmartAlbum.TimeRange>()
        if (timeAlbums.isNotEmpty()) {
            item {
                AlbumSection(
                    title = "📅 Time Capsules",
                    albums = timeAlbums,
                    onAlbumClick = onAlbumClick
                )
            }
        }

        // Face-based Albums
        val faceAlbums = smartAlbums.filterIsInstance<SmartAlbum.Tagged>()
            .filter { it.tagValue in listOf("group_photo", "selfie", "couple") }
        if (faceAlbums.isNotEmpty()) {
            item {
                AlbumSection(
                    title = "👥 People & Groups",
                    albums = faceAlbums,
                    onAlbumClick = onAlbumClick
                )
            }
        }

        // Relationship Albums
        val relationshipAlbums = smartAlbums.filterIsInstance<SmartAlbum.Tagged>()
            .filter { it.tagValue in listOf("family", "friend", "colleague") }
        if (relationshipAlbums.isNotEmpty()) {
            item {
                AlbumSection(
                    title = "❤️ Relationships",
                    albums = relationshipAlbums,
                    onAlbumClick = onAlbumClick
                )
            }
        }

        // Time of Day Albums
        val timeOfDayAlbums = smartAlbums.filterIsInstance<SmartAlbum.Tagged>()
            .filter { it.tagValue in listOf("morning", "afternoon", "evening", "night") }
        if (timeOfDayAlbums.isNotEmpty()) {
            item {
                AlbumSection(
                    title = "🌅 Times of Day",
                    albums = timeOfDayAlbums,
                    onAlbumClick = onAlbumClick
                )
            }
        }

        // Scene Albums
        val sceneAlbums = smartAlbums.filterIsInstance<SmartAlbum.Tagged>()
            .filter { it.tagValue in listOf("indoor", "outdoor") }
        if (sceneAlbums.isNotEmpty()) {
            item {
                AlbumSection(
                    title = "🏞️ Scenes",
                    albums = sceneAlbums,
                    onAlbumClick = onAlbumClick
                )
            }
        }

        // Special Occasions
        val specialAlbums = smartAlbums.filterIsInstance<SmartAlbum.Tagged>()
            .filter { it.tagValue in listOf("birthday", "high_res") }
        if (specialAlbums.isNotEmpty()) {
            item {
                AlbumSection(
                    title = "⭐ Special",
                    albums = specialAlbums,
                    onAlbumClick = onAlbumClick
                )
            }
        }

        // Person Albums
        val personAlbums = smartAlbums.filterIsInstance<SmartAlbum.Person>()
        if (personAlbums.isNotEmpty()) {
            item {
                AlbumSection(
                    title = "👤 People",
                    albums = personAlbums,
                    onAlbumClick = onAlbumClick
                )
            }
        }
    }
}

/**
 * Stories section - circular album previews
 */
@Composable
private fun StoriesSection(
    albums: List<SmartAlbum>,
    onAlbumClick: (albumType: String, albumId: String) -> Unit
) {
    Column(
        modifier = Modifier.fillMaxWidth()
    ) {
        Text(
            text = "📖 Stories",
            style = MaterialTheme.typography.titleLarge,
            fontWeight = FontWeight.Bold,
            modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
        )

        LazyRow(
            contentPadding = PaddingValues(horizontal = 16.dp),
            horizontalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            items(albums) { album ->
                StoryCircle(
                    album = album,
                    onClick = {
                        val (type, id) = getAlbumNavigation(album)
                        onAlbumClick(type, id)
                    }
                )
            }
        }
    }
}

/**
 * Story circle - circular album preview
 */
@Composable
private fun StoryCircle(
    album: SmartAlbum,
    onClick: () -> Unit
) {
    val (icon, gradient) = getAlbumIconAndGradient(album)

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(8.dp),
        modifier = Modifier.clickable(onClick = onClick)
    ) {
        Box(
            modifier = Modifier
                .size(80.dp)
                .clip(CircleShape)
                .background(gradient),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                imageVector = icon,
                contentDescription = null,
                tint = Color.White,
                modifier = Modifier.size(36.dp)
            )
        }

        Text(
            text = album.displayName,
            style = MaterialTheme.typography.labelSmall,
            maxLines = 2,
            modifier = Modifier.width(80.dp),
            fontWeight = FontWeight.Medium,
            textAlign = androidx.compose.ui.text.style.TextAlign.Center
        )

        Text(
            text = "${album.imageCount}",
            style = MaterialTheme.typography.labelSmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

/**
 * Album section with horizontal scrolling rectangular cards
 */
@Composable
private fun AlbumSection(
    title: String,
    albums: List<SmartAlbum>,
    onAlbumClick: (albumType: String, albumId: String) -> Unit
) {
    Column(
        modifier = Modifier.fillMaxWidth()
    ) {
        Text(
            text = title,
            style = MaterialTheme.typography.titleLarge,
            fontWeight = FontWeight.Bold,
            modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
        )

        LazyRow(
            contentPadding = PaddingValues(horizontal = 16.dp),
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            items(albums) { album ->
                AlbumCard(
                    album = album,
                    onClick = {
                        val (type, id) = getAlbumNavigation(album)
                        onAlbumClick(type, id)
                    }
                )
            }
        }
    }
}

/**
 * Rectangular album card - compact design
 */
@Composable
private fun AlbumCard(
    album: SmartAlbum,
    onClick: () -> Unit
) {
    val (icon, gradient) = getAlbumIconAndGradient(album)

    Card(
        modifier = Modifier
            .width(180.dp)
            .height(120.dp)
            .clickable(onClick = onClick),
        shape = RoundedCornerShape(16.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(gradient)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                verticalArrangement = Arrangement.SpaceBetween
            ) {
                // Icon
                Icon(
                    imageVector = icon,
                    contentDescription = null,
                    tint = Color.White,
                    modifier = Modifier.size(32.dp)
                )

                // Album info
                Column {
                    Text(
                        text = album.displayName,
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                        color = Color.White,
                        maxLines = 1
                    )
                    Text(
                        text = "${album.imageCount} ${if (album.imageCount == 1) "photo" else "photos"}",
                        style = MaterialTheme.typography.bodySmall,
                        color = Color.White.copy(alpha = 0.9f)
                    )
                }
            }
        }
    }
}

/**
 * Empty state
 */
@Composable
private fun EmptyExploreView() {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .padding(32.dp),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Icon(
                Icons.Default.PhotoAlbum,
                contentDescription = null,
                modifier = Modifier.size(80.dp),
                tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
            )

            Text(
                "No Albums Yet",
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Bold
            )

            Text(
                "Add photos to your collection to see smart albums",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                textAlign = androidx.compose.ui.text.style.TextAlign.Center
            )
        }
    }
}

/**
 * Get navigation parameters for album
 */
private fun getAlbumNavigation(album: SmartAlbum): Pair<String, String> {
    return when (album) {
        is SmartAlbum.TimeRange.Today -> "time" to "today"
        is SmartAlbum.TimeRange.ThisWeek -> "time" to "week"
        is SmartAlbum.TimeRange.ThisMonth -> "time" to "month"
        is SmartAlbum.TimeRange.LastYear -> "time" to "year"
        is SmartAlbum.Tagged -> "tag" to album.tagValue
        is SmartAlbum.Person -> "person" to album.personId
    }
}

/**
 * Get icon and gradient for album type
 */
private fun getAlbumIconAndGradient(album: SmartAlbum): Pair<ImageVector, Brush> {
    return when (album) {
        is SmartAlbum.TimeRange.Today -> Icons.Default.Today to gradientBlue()
        is SmartAlbum.TimeRange.ThisWeek -> Icons.Default.DateRange to gradientTeal()
        is SmartAlbum.TimeRange.ThisMonth -> Icons.Default.CalendarMonth to gradientGreen()
        is SmartAlbum.TimeRange.LastYear -> Icons.Default.HistoryEdu to gradientPurple()
        is SmartAlbum.Tagged -> when (album.tagValue) {
            "group_photo" -> Icons.Default.Group to gradientOrange()
            "selfie" -> Icons.Default.CameraAlt to gradientPink()
            "couple" -> Icons.Default.Favorite to gradientRed()
            "family" -> Icons.Default.FamilyRestroom to gradientIndigo()
            "friend" -> Icons.Default.People to gradientCyan()
            "colleague" -> Icons.Default.BusinessCenter to gradientGray()
            "morning" -> Icons.Default.WbSunny to gradientYellow()
            "afternoon" -> Icons.Default.LightMode to gradientOrange()
            "evening" -> Icons.Default.WbTwilight to gradientOrange()
            "night" -> Icons.Default.NightsStay to gradientDarkBlue()
            "outdoor" -> Icons.Default.Landscape to gradientGreen()
            "indoor" -> Icons.Default.Home to gradientBrown()
            "birthday" -> Icons.Default.Cake to gradientPink()
            "high_res" -> Icons.Default.HighQuality to gradientGold()
            else -> Icons.Default.Label to gradientBlue()
        }
        is SmartAlbum.Person -> Icons.Default.Person to gradientPurple()
    }
}

// Gradient helpers
private fun gradientBlue() = Brush.linearGradient(listOf(Color(0xFF1976D2), Color(0xFF1565C0)))
private fun gradientTeal() = Brush.linearGradient(listOf(Color(0xFF00897B), Color(0xFF00796B)))
private fun gradientGreen() = Brush.linearGradient(listOf(Color(0xFF388E3C), Color(0xFF2E7D32)))
private fun gradientPurple() = Brush.linearGradient(listOf(Color(0xFF7B1FA2), Color(0xFF6A1B9A)))
private fun gradientOrange() = Brush.linearGradient(listOf(Color(0xFFF57C00), Color(0xFFE64A19)))
private fun gradientPink() = Brush.linearGradient(listOf(Color(0xFFD81B60), Color(0xFFC2185B)))
private fun gradientRed() = Brush.linearGradient(listOf(Color(0xFFE53935), Color(0xFFD32F2F)))
private fun gradientIndigo() = Brush.linearGradient(listOf(Color(0xFF3949AB), Color(0xFF303F9F)))
private fun gradientCyan() = Brush.linearGradient(listOf(Color(0xFF00ACC1), Color(0xFF0097A7)))
private fun gradientGray() = Brush.linearGradient(listOf(Color(0xFF616161), Color(0xFF424242)))
private fun gradientYellow() = Brush.linearGradient(listOf(Color(0xFFFDD835), Color(0xFFFBC02D)))
private fun gradientDarkBlue() = Brush.linearGradient(listOf(Color(0xFF283593), Color(0xFF1A237E)))
private fun gradientBrown() = Brush.linearGradient(listOf(Color(0xFF5D4037), Color(0xFF4E342E)))
private fun gradientGold() = Brush.linearGradient(listOf(Color(0xFFFFB300), Color(0xFFFFA000)))