package eu.geyskens.pdfscan.ui.screens

import android.Manifest
import android.graphics.PointF
import android.media.AudioManager
import android.media.MediaActionSound
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.resolutionselector.AspectRatioStrategy
import androidx.camera.core.resolutionselector.ResolutionSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledIconButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.concurrent.futures.await
import androidx.core.content.ContextCompat
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.rememberPermissionState
import eu.geyskens.pdfscan.R
import eu.geyskens.pdfscan.Routes
import eu.geyskens.pdfscan.ScanViewModel
import eu.geyskens.pdfscan.scan.DocumentAnalyzer
import kotlinx.coroutines.launch
import java.io.File
import java.util.concurrent.Executors

@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun CameraScreen(vm: ScanViewModel, navController: androidx.navigation.NavController) {
    val cameraPermission = rememberPermissionState(Manifest.permission.CAMERA)

    Box(Modifier.fillMaxSize().background(Color.Black)) {
        if (cameraPermission.status.isGranted) {
            CameraContent(vm, navController)
        } else {
            PermissionRequest(onRequest = { cameraPermission.launchPermissionRequest() })
        }
    }
}

@Composable
private fun PermissionRequest(onRequest: () -> Unit) {
    Box(Modifier.fillMaxSize().padding(32.dp), contentAlignment = Alignment.Center) {
        androidx.compose.foundation.layout.Column(horizontalAlignment = Alignment.CenterHorizontally) {
            Text(
                stringResource(R.string.camera_permission_rationale),
                color = Color.White,
                textAlign = TextAlign.Center,
            )
            androidx.compose.foundation.layout.Spacer(Modifier.size(16.dp))
            Button(onClick = onRequest) { Text(stringResource(R.string.grant_access)) }
        }
    }
}

@Composable
private fun CameraContent(vm: ScanViewModel, navController: androidx.navigation.NavController) {
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current
    val scope = rememberCoroutineScope()
    val pages by vm.pages.collectAsState()

    val executor = remember { Executors.newSingleThreadExecutor() }
    // Same 4:3 aspect for preview and analysis so the live overlay lines up with the preview.
    val resolutionSelector = remember {
        ResolutionSelector.Builder()
            .setAspectRatioStrategy(AspectRatioStrategy.RATIO_4_3_FALLBACK_AUTO_STRATEGY)
            .build()
    }
    val imageCapture = remember {
        ImageCapture.Builder()
            .setCaptureMode(ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY)
            .build()
    }
    val imageAnalysis = remember {
        ImageAnalysis.Builder()
            .setResolutionSelector(resolutionSelector)
            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
            .build()
    }
    var capturing by remember { mutableStateOf(false) }
    // Live document corners (normalized, display-oriented) + the analysis frame aspect ratio.
    var liveCorners by remember { mutableStateOf<List<PointF>?>(null) }
    var frameAspect by remember { mutableStateOf(0f) }

    // Capture feedback: system shutter sound + a brief white flash over the preview,
    // so there's clear confirmation even when the phone is on silent.
    val shutterSound = remember { MediaActionSound().apply { load(MediaActionSound.SHUTTER_CLICK) } }
    val audioManager = remember { ContextCompat.getSystemService(context, AudioManager::class.java) }
    val flash = remember { Animatable(0f) }
    var captureTick by remember { mutableIntStateOf(0) }
    androidx.compose.runtime.LaunchedEffect(captureTick) {
        if (captureTick > 0) {
            flash.snapTo(0.75f)
            flash.animateTo(0f, tween(320))
        }
    }
    androidx.compose.runtime.DisposableEffect(Unit) {
        onDispose { shutterSound.release() }
    }

    val previewView = remember {
        PreviewView(context).apply {
            scaleType = PreviewView.ScaleType.FILL_CENTER
            // TextureView mode so the Compose overlay draws on top of the preview
            // (SurfaceView mode composites on a separate layer that hides the overlay).
            implementationMode = PreviewView.ImplementationMode.COMPATIBLE
        }
    }

    androidx.compose.runtime.LaunchedEffect(Unit) {
        val provider = ProcessCameraProvider.getInstance(context).await()
        val preview = Preview.Builder()
            .setResolutionSelector(resolutionSelector)
            .build()
            .also { it.setSurfaceProvider(previewView.surfaceProvider) }
        imageAnalysis.setAnalyzer(executor, DocumentAnalyzer { corners, aspect ->
            liveCorners = corners
            frameAspect = aspect
        })
        provider.unbindAll()
        provider.bindToLifecycle(
            lifecycleOwner, CameraSelector.DEFAULT_BACK_CAMERA, preview, imageCapture, imageAnalysis
        )
    }

    Box(Modifier.fillMaxSize()) {
        androidx.compose.ui.viewinterop.AndroidView(
            factory = { previewView },
            modifier = Modifier.fillMaxSize(),
        )

        // Live edge-detection overlay, mapped onto the FILL_CENTER-cropped preview.
        Canvas(Modifier.fillMaxSize()) {
            val corners = liveCorners
            if (corners != null && corners.size == 4 && frameAspect > 0f) {
                val viewAspect = size.width / size.height
                val dispW: Float
                val dispH: Float
                if (frameAspect > viewAspect) {
                    dispH = size.height; dispW = size.height * frameAspect
                } else {
                    dispW = size.width; dispH = size.width / frameAspect
                }
                val offX = (size.width - dispW) / 2f
                val offY = (size.height - dispH) / 2f
                val pts = corners.map { Offset(offX + it.x * dispW, offY + it.y * dispH) }
                for (i in pts.indices) {
                    drawLine(Color(0xFF00E676), pts[i], pts[(i + 1) % 4], strokeWidth = 5f)
                }
            }
        }

        // Top bar: settings.
        IconButton(
            onClick = { navController.navigate(Routes.SETTINGS) },
            modifier = Modifier.align(Alignment.TopEnd).statusBarsPadding().padding(8.dp),
        ) {
            Icon(Icons.Filled.Settings, contentDescription = stringResource(R.string.settings), tint = Color.White)
        }

        // Bottom controls.
        Row(
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .fillMaxWidth()
                .background(Color(0x66000000))
                .navigationBarsPadding()
                .padding(24.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            // Page count.
            Box(Modifier.size(56.dp), contentAlignment = Alignment.Center) {
                Text("${pages.size}", color = Color.White, style = MaterialTheme.typography.titleLarge)
            }

            // Shutter.
            FilledIconButton(
                onClick = {
                    if (capturing) return@FilledIconButton
                    capturing = true
                    // Flash always; play the shutter sound only when the ringer isn't silenced.
                    if (audioManager?.ringerMode == AudioManager.RINGER_MODE_NORMAL) {
                        shutterSound.play(MediaActionSound.SHUTTER_CLICK)
                    }
                    captureTick++
                    val file = File(vm.capturesDir(), "cap_${System.currentTimeMillis()}.jpg")
                    val options = ImageCapture.OutputFileOptions.Builder(file).build()
                    imageCapture.takePicture(
                        options,
                        ContextCompat.getMainExecutor(context),
                        object : ImageCapture.OnImageSavedCallback {
                            override fun onImageSaved(result: ImageCapture.OutputFileResults) {
                                scope.launch {
                                    vm.onImageCaptured(file)
                                    capturing = false
                                }
                            }

                            override fun onError(exception: ImageCaptureException) {
                                capturing = false
                            }
                        },
                    )
                },
                modifier = Modifier.size(76.dp),
                shape = CircleShape,
            ) {
                if (capturing) CircularProgressIndicator(Modifier.size(28.dp), color = Color.White)
            }

            // Done -> pages.
            IconButton(
                onClick = { if (pages.isNotEmpty()) navController.navigate(Routes.PAGES) },
                modifier = Modifier.size(56.dp),
            ) {
                Icon(
                    Icons.Filled.Check,
                    contentDescription = stringResource(R.string.done),
                    tint = if (pages.isEmpty()) Color.Gray else Color.White,
                )
            }
        }

        // Shutter flash overlay (drawn on top, fades out quickly).
        if (flash.value > 0f) {
            Box(Modifier.fillMaxSize().background(Color.White.copy(alpha = flash.value)))
        }
    }

    androidx.compose.runtime.DisposableEffect(Unit) {
        onDispose { executor.shutdown() }
    }
}
