package com.placeholder.sherpai2

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.placeholder.sherpai2.domain.repository.ImageRepository
import com.placeholder.sherpai2.domain.usecase.PopulateFaceDetectionCacheUseCase
import com.placeholder.sherpai2.ui.presentation.MainScreen
import com.placeholder.sherpai2.ui.theme.SherpAI2Theme
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

/**
 * MainActivity - TWO-PHASE STARTUP
 *
 * Phase 1: Image ingestion (fast - just loads URIs)
 * Phase 2: Face detection cache (slower - scans for faces)
 *
 * App is usable immediately, both run in background.
 */
@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    @Inject
    lateinit var imageRepository: ImageRepository

    @Inject
    lateinit var populateFaceCache: PopulateFaceDetectionCacheUseCase

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val storagePermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            Manifest.permission.READ_MEDIA_IMAGES
        } else {
            Manifest.permission.READ_EXTERNAL_STORAGE
        }

        setContent {
            SherpAI2Theme {
                var hasPermission by remember {
                    mutableStateOf(
                        ContextCompat.checkSelfPermission(this@MainActivity, storagePermission) ==
                                PackageManager.PERMISSION_GRANTED
                    )
                }

                var ingestionState by remember { mutableStateOf<IngestionState>(IngestionState.NotStarted) }
                var cacheState by remember { mutableStateOf<CacheState>(CacheState.NotStarted) }

                val permissionLauncher = rememberLauncherForActivityResult(
                    ActivityResultContracts.RequestPermission()
                ) { granted ->
                    hasPermission = granted
                }

                // Phase 1: Image ingestion
                LaunchedEffect(hasPermission) {
                    if (hasPermission && ingestionState is IngestionState.NotStarted) {
                        ingestionState = IngestionState.InProgress(0, 0)

                        lifecycleScope.launch(Dispatchers.IO) {
                            try {
                                val existingCount = imageRepository.getImageCount()

                                if (existingCount > 0) {
                                    withContext(Dispatchers.Main) {
                                        ingestionState = IngestionState.Complete(existingCount)
                                    }
                                } else {
                                    imageRepository.ingestImagesWithProgress { current, total ->
                                        ingestionState = IngestionState.InProgress(current, total)
                                    }

                                    val finalCount = imageRepository.getImageCount()
                                    withContext(Dispatchers.Main) {
                                        ingestionState = IngestionState.Complete(finalCount)
                                    }
                                }
                            } catch (e: Exception) {
                                withContext(Dispatchers.Main) {
                                    ingestionState = IngestionState.Error(e.message ?: "Failed to load images")
                                }
                            }
                        }
                    } else if (!hasPermission) {
                        permissionLauncher.launch(storagePermission)
                    }
                }

                // Phase 2: Face detection cache population
                LaunchedEffect(ingestionState) {
                    if (ingestionState is IngestionState.Complete && cacheState is CacheState.NotStarted) {
                        lifecycleScope.launch(Dispatchers.IO) {
                            try {
                                // Check if cache needs population
                                val stats = populateFaceCache.getCacheStats()

                                if (stats.needsScanning == 0) {
                                    withContext(Dispatchers.Main) {
                                        cacheState = CacheState.Complete(stats.imagesWithFaces, stats.imagesWithoutFaces)
                                    }
                                } else {
                                    withContext(Dispatchers.Main) {
                                        cacheState = CacheState.InProgress(0, stats.needsScanning)
                                    }

                                    populateFaceCache.execute { current, total, _ ->
                                        cacheState = CacheState.InProgress(current, total)
                                    }

                                    val finalStats = populateFaceCache.getCacheStats()
                                    withContext(Dispatchers.Main) {
                                        cacheState = CacheState.Complete(
                                            finalStats.imagesWithFaces,
                                            finalStats.imagesWithoutFaces
                                        )
                                    }
                                }
                            } catch (e: Exception) {
                                withContext(Dispatchers.Main) {
                                    cacheState = CacheState.Error(e.message ?: "Failed to scan faces")
                                }
                            }
                        }
                    }
                }

                // UI
                Box(modifier = Modifier.fillMaxSize()) {
                    when {
                        hasPermission -> {
                            // Main screen always visible
                            MainScreen()

                            // Progress overlays at bottom with navigation bar clearance
                            Column(
                                modifier = Modifier
                                    .fillMaxSize()
                                    .padding(horizontal = 16.dp)
                                    .padding(bottom = 120.dp), // More space for nav bar + gestures
                                verticalArrangement = Arrangement.Bottom
                            ) {
                                if (ingestionState is IngestionState.InProgress) {
                                    IngestionProgressCard(ingestionState as IngestionState.InProgress)
                                    Spacer(Modifier.height(8.dp))
                                }

                                if (cacheState is CacheState.InProgress) {
                                    FaceCacheProgressCard(cacheState as CacheState.InProgress)
                                }
                            }
                        }
                        else -> {
                            Box(
                                modifier = Modifier.fillMaxSize(),
                                contentAlignment = Alignment.Center
                            ) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally,
                                    verticalArrangement = Arrangement.spacedBy(16.dp)
                                ) {
                                    Text(
                                        "Storage Permission Required",
                                        style = MaterialTheme.typography.titleLarge,
                                        fontWeight = FontWeight.Bold
                                    )
                                    Text(
                                        "SherpAI needs access to your photos",
                                        style = MaterialTheme.typography.bodyMedium
                                    )
                                    Button(onClick = { permissionLauncher.launch(storagePermission) }) {
                                        Text("Grant Permission")
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

sealed class IngestionState {
    object NotStarted : IngestionState()
    data class InProgress(val current: Int, val total: Int) : IngestionState()
    data class Complete(val imageCount: Int) : IngestionState()
    data class Error(val message: String) : IngestionState()
}

sealed class CacheState {
    object NotStarted : CacheState()
    data class InProgress(val current: Int, val total: Int) : CacheState()
    data class Complete(val withFaces: Int, val withoutFaces: Int) : CacheState()
    data class Error(val message: String) : CacheState()
}

@Composable
fun IngestionProgressCard(state: IngestionState.InProgress) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "Loading photos...",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold
                )

                if (state.total > 0) {
                    Text(
                        text = "${state.current} / ${state.total}",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.primary
                    )
                }
            }

            if (state.total > 0) {
                LinearProgressIndicator(
                    progress = { state.current.toFloat() / state.total.toFloat() },
                    modifier = Modifier.fillMaxWidth(),
                )
            } else {
                LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
            }

            Text(
                text = "You can use the app while photos load",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Composable
fun FaceCacheProgressCard(state: CacheState.InProgress) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.secondaryContainer
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "Scanning for faces...",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold
                )

                if (state.total > 0) {
                    Text(
                        text = "${state.current} / ${state.total}",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.secondary
                    )
                }
            }

            if (state.total > 0) {
                LinearProgressIndicator(
                    progress = { state.current.toFloat() / state.total.toFloat() },
                    modifier = Modifier.fillMaxWidth(),
                )
            } else {
                LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
            }

            Text(
                text = "Face filters will work once scanning completes",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}