package com.mybus17000.ui.screens

import android.content.Context
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Place
import androidx.compose.material.icons.filled.SwapVert
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.google.android.gms.maps.model.LatLng
import com.mybus17000.data.BusRoute
import com.mybus17000.data.fetchAddresses
import com.mybus17000.ui.screens.RouteViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RouteSearchScreen(
    navController: NavController,
    routeViewModel: RouteViewModel = androidx.lifecycle.viewmodel.compose.viewModel()
) {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()

    var fromText by remember { mutableStateOf(TextFieldValue("")) }
    var toText by remember { mutableStateOf(TextFieldValue("")) }

    var fromSuggestions by remember { mutableStateOf(listOf<String>()) }
    var toSuggestions by remember { mutableStateOf(listOf<String>()) }

    var showFromSuggestions by remember { mutableStateOf(false) }
    var showToSuggestions by remember { mutableStateOf(false) }

    // 🧠 Suggestion fetch avec debounce
    LaunchedEffect(fromText.text) {
        if (fromText.text.length >= 3) {
            delay(300)
            fromSuggestions = fetchAddresses(fromText.text)
            showFromSuggestions = fromSuggestions.isNotEmpty()
        } else {
            fromSuggestions = emptyList()
            showFromSuggestions = false
        }
    }

    LaunchedEffect(toText.text) {
        if (toText.text.length >= 3) {
            delay(300)
            toSuggestions = fetchAddresses(toText.text)
            showToSuggestions = toSuggestions.isNotEmpty()
        } else {
            toSuggestions = emptyList()
            showToSuggestions = false
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Recherche d’itinéraire") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Retour")
                    }
                }
            )
        }
    ) { padding ->
        Column(
            Modifier
                .padding(padding)
                .fillMaxSize()
                .padding(16.dp)
        ) {
            // 🔹 Champ Départ
            OutlinedTextField(
                value = fromText,
                onValueChange = { fromText = it },
                label = { Text("Départ") },
                leadingIcon = { Icon(Icons.Default.Place, null) },
                modifier = Modifier.fillMaxWidth()
            )

            AnimatedVisibility(
                visible = showFromSuggestions,
                enter = fadeIn() + expandVertically(),
                exit = fadeOut() + shrinkVertically()
            ) {
                LazyColumn {
                    items(fromSuggestions) { suggestion ->
                        TextButton(
                            onClick = {
                                fromText = TextFieldValue(suggestion)
                                showFromSuggestions = false
                            },
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text(suggestion, color = Color.Black)
                        }
                    }
                }
            }

            Spacer(Modifier.height(12.dp))

            // 🔁 Bouton pour échanger départ / arrivée
            IconButton(
                onClick = {
                    val tmp = fromText
                    fromText = toText
                    toText = tmp
                },
                modifier = Modifier.align(Alignment.CenterHorizontally)
            ) {
                Icon(Icons.Default.SwapVert, contentDescription = "Échanger", tint = Color(0xFF4285F4))
            }

            // 🔹 Champ Arrivée
            OutlinedTextField(
                value = toText,
                onValueChange = { toText = it },
                label = { Text("Arrivée") },
                leadingIcon = { Icon(Icons.Default.Place, null) },
                modifier = Modifier.fillMaxWidth()
            )

            AnimatedVisibility(
                visible = showToSuggestions,
                enter = fadeIn() + expandVertically(),
                exit = fadeOut() + shrinkVertically()
            ) {
                LazyColumn {
                    items(toSuggestions) { suggestion ->
                        TextButton(
                            onClick = {
                                toText = TextFieldValue(suggestion)
                                showToSuggestions = false
                            },
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text(suggestion, color = Color.Black)
                        }
                    }
                }
            }

            Spacer(Modifier.height(24.dp))

            // 🔘 Bouton Rechercher
            Button(
                onClick = {
                    routeViewModel.searchRoutes(fromText.text, toText.text, null, false)
                },
                modifier = Modifier.fillMaxWidth(),
                enabled = fromText.text.isNotBlank() && toText.text.isNotBlank()
            ) {
                Text("Rechercher un itinéraire")
            }

            Spacer(Modifier.height(24.dp))

            // 🚌 Résultats
            val routes by routeViewModel.routes.collectAsState(initial = emptyList())
            val isLoading by routeViewModel.isLoading.collectAsState(initial = false)
            val error by routeViewModel.error.collectAsState(initial = null)

            when {
                isLoading -> CircularProgressIndicator(Modifier.align(Alignment.CenterHorizontally))
                error != null -> Text("Erreur : $error", color = Color.Red)
                routes.isNotEmpty() -> LazyColumn {
                    items(routes) { route ->
                        RouteCard(route)
                        Spacer(Modifier.height(8.dp))
                    }
                }
            }
        }
    }
}


@Composable
fun RouteCard(route: BusRoute) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(containerColor = Color(0xFFF5F5F5)),
        elevation = CardDefaults.cardElevation(4.dp)
    ) {
        Column(Modifier.padding(12.dp)) {
            Text(
                text = "🕒 Durée : ${route.totalDuration} min — ${route.numberOfChanges} correspondance(s)",
                style = MaterialTheme.typography.bodyMedium,
                color = Color(0xFF1976D2)
            )

            Spacer(Modifier.height(8.dp))

            route.segments.forEach { segment ->
                Text("🚍 ${segment.lineName} : ${segment.fromStop} → ${segment.toStop}")
                Text("   ${segment.departureTime} - ${segment.arrivalTime}", color = Color.Gray)
                Spacer(Modifier.height(6.dp))
            }
        }
    }
}