package com.example.ui.planning import android.Manifest import android.app.Activity import android.content.pm.PackageManager import android.net.Uri import android.util.Log import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.CalendarMonth import androidx.compose.material.icons.filled.CameraAlt import androidx.compose.material.icons.filled.Kitchen import androidx.compose.material.icons.filled.PhotoLibrary import androidx.compose.material.icons.filled.ShoppingCart import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilterChip import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.SegmentedButton import androidx.compose.material3.SegmentedButtonDefaults import androidx.compose.material3.SingleChoiceSegmentedButtonRow import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat import com.example.data.model.CustomFoodEntry import com.example.data.model.FoodCategory import com.example.data.model.FoodUnit import com.example.data.model.InventoryItem import com.example.data.model.MealType import com.example.data.model.MenuAdaptationUiState import com.example.data.model.PlannedMealEntry import com.example.data.model.PredictionMealScope import com.example.data.model.ReceiptScanUiState import com.example.data.model.RecipeEntry import com.example.data.model.ScannedReceiptItem import com.example.data.model.ShoppingListItem import com.example.data.model.StorageLocation import com.example.data.model.WeekPredictionUiState import com.example.util.ImageUtils import kotlinx.coroutines.launch import java.time.LocalDate enum class PlanningSubTab(val label: String) { WEEK("Semaine"), STOCK("Stock"), SHOPPING("Courses") } @OptIn(ExperimentalMaterial3Api::class) @Composable fun PlanningScreen( weekStartDate: LocalDate, plannedMeals: List, inventoryItems: List, shoppingItems: List, recipes: List, customFoods: List, receiptScanState: ReceiptScanUiState, weekPredictionState: WeekPredictionUiState, expiringSoonItems: List = emptyList(), expirationAlertDays: Int = 3, menuAdaptationState: MenuAdaptationUiState = MenuAdaptationUiState.Idle, onPreviousWeek: () -> Unit, onNextWeek: () -> Unit, onGoToCurrentWeek: () -> Unit, onSavePlannedMeal: (PlannedMealEntry) -> Unit, onDeletePlannedMeal: (String) -> Unit, onMarkPlannedMealAsEaten: (PlannedMealEntry) -> Unit, onAddCustomFood: (String, FoodUnit, List) -> Unit, onSaveInventoryItem: (InventoryItem) -> Unit, onAdjustInventoryQuantity: (itemId: String, delta: Double) -> Unit, onDeleteInventoryItem: (itemId: String) -> Unit, onAddManualShoppingItem: (name: String, quantity: Double?, unit: FoodUnit, category: FoodCategory) -> Unit, onToggleShoppingItemChecked: (ShoppingListItem, Boolean) -> Unit, onAddShoppingItemToStock: (ShoppingListItem, Double, FoodUnit, StorageLocation) -> Unit, onFinishShoppingAndAddToStock: (List, Map) -> Unit, onDeleteManualShoppingItem: (String) -> Unit, onClearCheckedShoppingItems: () -> Unit, onPredictWeekMeals: (PredictionMealScope, Double) -> Unit, onTogglePredictedMeal: (String) -> Unit, onUpdatePredictedMealServings: (String, Double) -> Unit, onConfirmPredictedMeals: () -> Unit, onDismissWeekPrediction: () -> Unit, onAdaptMenusForExpiring: () -> Unit = {}, onToggleMenuAdaptation: (String) -> Unit = {}, onConfirmMenuAdaptations: () -> Unit = {}, onDismissMenuAdaptation: () -> Unit = {}, onScanReceiptUri: (Uri) -> Unit, onUpdateScannedItem: (ScannedReceiptItem) -> Unit, onRemoveScannedItem: (String) -> Unit, onAddBlankScannedItem: () -> Unit, onConfirmReceiptImport: (List, Boolean) -> Unit, onDismissReceiptScan: () -> Unit, onShowMessage: (String) -> Unit ) { val context = LocalContext.current var activeSubTab by rememberSaveable { mutableStateOf(PlanningSubTab.WEEK) } // Sheet & Dialog states var planTargetDate by remember { mutableStateOf(null) } var planTargetMealType by remember { mutableStateOf(MealType.LUNCH) } var editingPlannedMeal by remember { mutableStateOf(null) } var showInventoryEditor by remember { mutableStateOf(false) } var editingInventoryItem by remember { mutableStateOf(null) } var showReceiptSourceDialog by remember { mutableStateOf(false) } var pendingCaptureUriString by rememberSaveable { mutableStateOf(null) } val coroutineScope = rememberCoroutineScope() var shoppingItemForStockPrompt by remember { mutableStateOf(null) } var showPredictWeekSheet by rememberSaveable { mutableStateOf(false) } var showShoppingMode by rememberSaveable { mutableStateOf(false) } val recipesById = remember(recipes) { recipes.associateBy { it.id } } // Zero-permission Photo Picker for Gallery receipt image val pickReceiptLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.PickVisualMedia() ) { uri -> if (uri != null) { onScanReceiptUri(uri) } } // Camera capture via FileProvider URI with explicit read/write grants + OEM fallback handling val takeReceiptPhotoLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.StartActivityForResult() ) { result -> val expectedUri = pendingCaptureUriString?.let(Uri::parse) pendingCaptureUriString = null if (result.resultCode == Activity.RESULT_OK) { val resultData = result.data coroutineScope.launch { val resolvedUri = ImageUtils.resolveCapturedReceiptUri( context = context, expectedUri = expectedUri, resultData = resultData ) if (resolvedUri != null) { onScanReceiptUri(resolvedUri) } else { onShowMessage("Impossible de récupérer la photo prise. Réessayez ou choisissez depuis la galerie.") } } } } val launchCameraCapture = { try { val uri = ImageUtils.createReceiptCaptureUri(context) pendingCaptureUriString = uri.toString() val captureIntent = ImageUtils.buildCameraCaptureIntent(context, uri) takeReceiptPhotoLauncher.launch(captureIntent) } catch (e: Exception) { pendingCaptureUriString = null Log.e("PlanningScreen", "Failed to launch camera capture", e) onShowMessage("Impossible d'ouvrir l'appareil photo") } } val cameraPermissionLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.RequestPermission() ) { granted -> if (granted) { launchCameraCapture() } else { onShowMessage("Autorisation caméra refusée — vous pouvez choisir une photo depuis la galerie") } } val triggerCameraReceiptScan = { val hasCameraPerm = ContextCompat.checkSelfPermission( context, Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED if (hasCameraPerm) { launchCameraCapture() } else { cameraPermissionLauncher.launch(Manifest.permission.CAMERA) } } val triggerGalleryReceiptScan = { pickReceiptLauncher.launch( PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) ) } val uncheckedShoppingCount = shoppingItems.count { !it.isChecked } Box( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.background) .testTag("planning_screen") ) { Column(modifier = Modifier.fillMaxSize()) { // Header + 3-segment switcher Column( modifier = Modifier .fillMaxWidth() .padding(start = 20.dp, end = 20.dp, top = 16.dp, bottom = 8.dp), verticalArrangement = Arrangement.spacedBy(12.dp) ) { Column { Text( text = when (activeSubTab) { PlanningSubTab.WEEK -> "Planning de la semaine" PlanningSubTab.STOCK -> "Mon Stock Cuisine" PlanningSubTab.SHOPPING -> "Liste de Courses" }, style = MaterialTheme.typography.headlineMedium, color = MaterialTheme.colorScheme.onBackground, fontWeight = FontWeight.Bold ) Text( text = when (activeSubTab) { PlanningSubTab.WEEK -> "Organisez vos repas et marquez-les consommés en 1 clic" PlanningSubTab.STOCK -> "Suivez vos ingrédients disponibles et scannez vos tickets" PlanningSubTab.SHOPPING -> "Vos besoins de la semaine ajustés selon votre stock" }, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) } SingleChoiceSegmentedButtonRow( modifier = Modifier .fillMaxWidth() .testTag("planning_subtab_row") ) { PlanningSubTab.entries.forEachIndexed { index, subTab -> val badgeSuffix = when (subTab) { PlanningSubTab.WEEK -> "" PlanningSubTab.STOCK -> if (inventoryItems.isNotEmpty()) " (${inventoryItems.size})" else "" PlanningSubTab.SHOPPING -> if (uncheckedShoppingCount > 0) " ($uncheckedShoppingCount)" else "" } SegmentedButton( selected = activeSubTab == subTab, onClick = { activeSubTab = subTab }, shape = SegmentedButtonDefaults.itemShape( index = index, count = PlanningSubTab.entries.size ), icon = { Icon( imageVector = when (subTab) { PlanningSubTab.WEEK -> Icons.Default.CalendarMonth PlanningSubTab.STOCK -> Icons.Default.Kitchen PlanningSubTab.SHOPPING -> Icons.Default.ShoppingCart }, contentDescription = null, modifier = Modifier.size(16.dp) ) }, modifier = Modifier.testTag("planning_subtab_${subTab.name.lowercase()}") ) { Text( text = "${subTab.label}$badgeSuffix", maxLines = 1 ) } } } } // Active sub-tab content Box(modifier = Modifier.weight(1f)) { when (activeSubTab) { PlanningSubTab.WEEK -> { WeeklyPlanTab( weekStartDate = weekStartDate, plannedMeals = plannedMeals, recipesById = recipesById, customFoods = customFoods, expiringSoonItems = expiringSoonItems, onPreviousWeek = onPreviousWeek, onNextWeek = onNextWeek, onGoToCurrentWeek = onGoToCurrentWeek, onPredictWeekClick = { showPredictWeekSheet = true }, onAdaptMenusForExpiringClick = onAdaptMenusForExpiring, onPlanMealClick = { date, mealType -> editingPlannedMeal = null planTargetDate = date planTargetMealType = mealType }, onEditPlannedMeal = { entry -> editingPlannedMeal = entry planTargetDate = LocalDate.ofEpochDay(entry.dateEpochDay) planTargetMealType = entry.mealType }, onDeletePlannedMeal = onDeletePlannedMeal, onMarkAsEaten = onMarkPlannedMealAsEaten ) } PlanningSubTab.STOCK -> { InventoryTab( inventoryItems = inventoryItems, alertThresholdDays = expirationAlertDays, onScanReceiptClick = { showReceiptSourceDialog = true }, onAddManualClick = { editingInventoryItem = null showInventoryEditor = true }, onAdaptMenusForExpiringClick = onAdaptMenusForExpiring, onEditItem = { item -> editingInventoryItem = item showInventoryEditor = true }, onAdjustQuantity = onAdjustInventoryQuantity, onDeleteItem = onDeleteInventoryItem ) } PlanningSubTab.SHOPPING -> { ShoppingListTab( shoppingItems = shoppingItems, hasPlannedMeals = plannedMeals.isNotEmpty(), onAddManualItem = onAddManualShoppingItem, onToggleItemChecked = { item, nowChecked -> if (nowChecked) { shoppingItemForStockPrompt = item } else { onToggleShoppingItemChecked(item, false) } }, onDeleteManualItem = onDeleteManualShoppingItem, onClearChecked = onClearCheckedShoppingItems, onScanReceiptClick = { showReceiptSourceDialog = true }, onOpenShoppingModeClick = { showShoppingMode = true }, onPredictWeekClick = { activeSubTab = PlanningSubTab.WEEK showPredictWeekSheet = true } ) } } } } } // Plan Meal Sheet val activePlanDate = planTargetDate if (activePlanDate != null) { PlanMealSheet( targetDate = activePlanDate, initialMealType = planTargetMealType, initialEntry = editingPlannedMeal, recipes = recipes, customFoods = customFoods, onAddCustomFood = onAddCustomFood, onDismiss = { planTargetDate = null editingPlannedMeal = null }, onSave = { entry -> planTargetDate = null editingPlannedMeal = null onSavePlannedMeal(entry) } ) } // Inventory Item Editor Sheet if (showInventoryEditor) { InventoryItemEditorSheet( initialItem = editingInventoryItem, onDismiss = { showInventoryEditor = false editingInventoryItem = null }, onSave = { item -> showInventoryEditor = false editingInventoryItem = null onSaveInventoryItem(item) }, onDelete = { id -> showInventoryEditor = false editingInventoryItem = null onDeleteInventoryItem(id) } ) } // Receipt Source Chooser Dialog (Camera vs Gallery) if (showReceiptSourceDialog) { AlertDialog( onDismissRequest = { showReceiptSourceDialog = false }, modifier = Modifier.testTag("receipt_source_dialog"), title = { Text( text = "Scanner un ticket de caisse", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold ) }, text = { Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { Text( text = "Prenez votre ticket bien à plat et éclairé. Seuls les aliments seront extraits et proposés à la vérification avant ajout au stock.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant ) Spacer(modifier = Modifier.height(4.dp)) Button( onClick = { showReceiptSourceDialog = false triggerCameraReceiptScan() }, shape = RoundedCornerShape(12.dp), modifier = Modifier .fillMaxWidth() .testTag("receipt_source_camera_button") ) { Icon(Icons.Default.CameraAlt, contentDescription = null) Spacer(modifier = Modifier.width(8.dp)) Text("Prendre une photo") } OutlinedButton( onClick = { showReceiptSourceDialog = false triggerGalleryReceiptScan() }, shape = RoundedCornerShape(12.dp), modifier = Modifier .fillMaxWidth() .testTag("receipt_source_gallery_button") ) { Icon(Icons.Default.PhotoLibrary, contentDescription = null) Spacer(modifier = Modifier.width(8.dp)) Text("Choisir depuis la galerie") } } }, confirmButton = {}, dismissButton = { TextButton(onClick = { showReceiptSourceDialog = false }) { Text("Annuler") } } ) } // Receipt Review Sheet (Scanning / Error / Preview) ReceiptReviewSheet( scanState = receiptScanState, onUpdateItem = onUpdateScannedItem, onRemoveItem = onRemoveScannedItem, onAddBlankItem = onAddBlankScannedItem, onConfirmImport = onConfirmReceiptImport, onRetryScan = { onDismissReceiptScan() showReceiptSourceDialog = true }, onDismiss = onDismissReceiptScan ) // Shopping Check -> Add to Stock Prompt Dialog val promptItem = shoppingItemForStockPrompt if (promptItem != null) { AddPurchasedItemToStockDialog( item = promptItem, onDismiss = { shoppingItemForStockPrompt = null }, onCheckOnly = { onToggleShoppingItemChecked(promptItem, true) shoppingItemForStockPrompt = null }, onAddToStock = { qty, unit, location -> onAddShoppingItemToStock(promptItem, qty, unit, location) shoppingItemForStockPrompt = null } ) } // AI Weekly Meal Prediction Sheet if (showPredictWeekSheet || weekPredictionState !is WeekPredictionUiState.Idle) { PredictWeekSheet( weekStartDate = weekStartDate, existingWeekMeals = plannedMeals, predictionState = weekPredictionState, onGenerate = { scope, servings -> onPredictWeekMeals(scope, servings) }, onToggleProposal = onTogglePredictedMeal, onUpdateServings = onUpdatePredictedMealServings, onConfirm = { onConfirmPredictedMeals() showPredictWeekSheet = false }, onResetToConfig = { onDismissWeekPrediction() }, onDismiss = { showPredictWeekSheet = false onDismissWeekPrediction() } ) } // AI Expiring-Stock Menu Adaptation Sheet AdaptMenusForExpiringSheet( adaptationState = menuAdaptationState, onToggleProposal = onToggleMenuAdaptation, onConfirm = onConfirmMenuAdaptations, onRetry = onAdaptMenusForExpiring, onDismiss = onDismissMenuAdaptation ) // Fullscreen In-Store Shopping Mode if (showShoppingMode) { ShoppingModeScreen( shoppingItems = shoppingItems, onToggleItemChecked = onToggleShoppingItemChecked, onAddQuickItem = { name, category -> onAddManualShoppingItem(name, null, FoodUnit.PORTION, category) }, onFinishAndAddToStock = onFinishShoppingAndAddToStock, onScanReceiptInstead = { showReceiptSourceDialog = true }, onDismiss = { showShoppingMode = false } ) } } @Composable private fun AddPurchasedItemToStockDialog( item: ShoppingListItem, onDismiss: () -> Unit, onCheckOnly: () -> Unit, onAddToStock: (quantity: Double, unit: FoodUnit, location: StorageLocation) -> Unit ) { val defaultQty = item.missingQuantity?.takeIf { it > 0.0 } ?: 1.0 var qtyText by remember(item.key) { mutableStateOf( if (defaultQty % 1.0 == 0.0) defaultQty.toInt().toString() else defaultQty.toString() ) } var selectedUnit by remember(item.key) { mutableStateOf(item.unit) } var selectedLocation by remember(item.key) { mutableStateOf(StorageLocation.defaultForCategory(item.category)) } val parsedQty = qtyText.replace(',', '.').toDoubleOrNull()?.takeIf { it > 0.0 } AlertDialog( onDismissRequest = onDismiss, modifier = Modifier.testTag("add_purchased_to_stock_dialog"), title = { Text( text = "Ajouter « ${item.name} » au stock ?", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold ) }, text = { Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { Text( text = "Vous venez de cocher cet article. Voulez-vous l'ajouter directement dans votre stock cuisine ?", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(6.dp) ) { OutlinedTextField( value = qtyText, onValueChange = { qtyText = it }, label = { Text("Quantité") }, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), shape = RoundedCornerShape(12.dp), modifier = Modifier.weight(1f) ) FoodUnit.entries.forEach { unit -> FilterChip( selected = selectedUnit == unit, onClick = { selectedUnit = unit }, label = { Text(unit.label) } ) } } Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(6.dp) ) { StorageLocation.entries.forEach { loc -> FilterChip( selected = selectedLocation == loc, onClick = { selectedLocation = loc }, label = { Text(loc.displayName) }, modifier = Modifier.weight(1f) ) } } } }, confirmButton = { Button( onClick = { onAddToStock(parsedQty ?: 1.0, selectedUnit, selectedLocation) }, enabled = parsedQty != null, modifier = Modifier.testTag("confirm_add_purchased_to_stock") ) { Text("Ajouter au stock") } }, dismissButton = { TextButton( onClick = onCheckOnly, modifier = Modifier.testTag("check_only_shopping_item") ) { Text("Cocher seulement") } } ) }