package com.mybus17000.ui.screens

import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Flag
import androidx.compose.material.icons.filled.Place
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
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.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.google.android.gms.maps.model.LatLng
import com.mybus17000.data.DropdownSuggestions
import com.mybus17000.data.StopFields
import com.mybus17000.data.findNearestStopWithDistance
import com.mybus17000.data.findNearestStops
import com.mybus17000.data.geocodeAddressSuggestions
import com.mybus17000.data.geocodeAddressSuspend
import kotlinx.coroutines.launch
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

@Composable
fun RouteSearchBar(
    fromQuery: String,
    toQuery: String,
    onFromChange: (String) -> Unit,
    onToChange: (String) -> Unit,
    selectedTime: LocalDateTime,
    onTimeChange: (LocalDateTime) -> Unit,
    onSearch: () -> Unit
) {
    Column(Modifier.padding(16.dp)) {
        TextField(
            value = fromQuery,
            onValueChange = onFromChange,
            placeholder = { Text("Départ") },
            modifier = Modifier.fillMaxWidth()
        )

        Spacer(Modifier.height(8.dp))

        TextField(
            value = toQuery,
            onValueChange = onToChange,
            placeholder = { Text("Arrivée") },
            modifier = Modifier.fillMaxWidth()
        )

        Spacer(Modifier.height(8.dp))

        Row(verticalAlignment = Alignment.CenterVertically) {
            Text("Heure : ${selectedTime.format(DateTimeFormatter.ofPattern("HH:mm"))}")
            Spacer(Modifier.width(8.dp))
            Button(onClick = onSearch) {
                Text("Rechercher l’itinéraire")
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RouteSearchPanel(
    stops: List<StopFields>,
    onValidate: (LatLng, LatLng) -> Unit
) {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()

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

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

    var fromNearestStops by remember { mutableStateOf<List<Pair<StopFields, Double>>>(emptyList()) }
    var toNearestStops by remember { mutableStateOf<List<Pair<StopFields, Double>>>(emptyList()) }

    val prefs = remember { context.getSharedPreferences("route_history", Context.MODE_PRIVATE) }
    var history by remember { mutableStateOf(prefs.getStringSet("recent_addresses", emptySet())!!.toList()) }

    fun saveToHistory(address: String) {
        if (address.isNotBlank()) {
            val updated = (history + address).distinct().takeLast(10)
            prefs.edit().putStringSet("recent_addresses", updated.toSet()).apply()
            history = updated
        }
    }

    Column(
        Modifier
            .fillMaxWidth()
            .padding(16.dp)
    ) {
        Text("🚌 Itinéraire", style = MaterialTheme.typography.titleMedium)
        Spacer(Modifier.height(8.dp))

        // === Champ de départ ===
        OutlinedTextField(
            value = fromText,
            onValueChange = { query ->
                fromText = query
                fromSuggestions = buildSuggestions(query, stops, history)
            },
            label = { Text("Adresse ou arrêt de départ") },
            modifier = Modifier.fillMaxWidth(),
            singleLine = true,
            shape = RoundedCornerShape(12.dp),
            leadingIcon = { Icon(Icons.Default.Place, contentDescription = null) },
            colors = TextFieldDefaults.colors()
        )

        SuggestionList(
            suggestions = fromSuggestions,
            onSelect = { selected ->
                fromText = selected
                fromSuggestions = emptyList()
                coroutineScope.launch {
                    val start = geocodeAddressSuspend(context, selected)
                    start?.let {
                        fromNearestStops = findNearestStops(it, stops, 4)
                    }
                }
            }
        )

        // 🟢 Affiche les 2 arrêts les plus proches du départ
        fromNearestStops.forEachIndexed { index, (stop, distance) ->
            Text(
                text = "🚏 ${stop.stop_name} — ${distance.toInt()} m",
                style = MaterialTheme.typography.bodySmall,
                color = if (index == 0) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(start = 12.dp, top = 2.dp)
            )
        }

        Spacer(Modifier.height(8.dp))

        // === Champ d’arrivée ===
        OutlinedTextField(
            value = toText,
            onValueChange = { query ->
                toText = query
                toSuggestions = buildSuggestions(query, stops, history)
            },
            label = { Text("Adresse ou arrêt d’arrivée") },
            modifier = Modifier.fillMaxWidth(),
            singleLine = true,
            shape = RoundedCornerShape(12.dp),
            leadingIcon = { Icon(Icons.Default.Flag, contentDescription = null) },
            colors = TextFieldDefaults.colors()
        )

        SuggestionList(
            suggestions = toSuggestions,
            onSelect = { selected ->
                toText = selected
                toSuggestions = emptyList()
                coroutineScope.launch {
                    val end = geocodeAddressSuspend(context, selected)
                    end?.let {
                        toNearestStops = findNearestStops(it, stops, 3)
                    }
                }
            }
        )

        // 🔴 Affiche les 2 arrêts les plus proches de l’arrivée
        toNearestStops.forEachIndexed { index, (stop, distance) ->
            Text(
                text = "🚏 ${stop.stop_name} — ${distance.toInt()} m",
                style = MaterialTheme.typography.bodySmall,
                color = if (index == 0) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(start = 12.dp, top = 2.dp)
            )
        }

        Spacer(Modifier.height(16.dp))

        Button(
            onClick = {
                coroutineScope.launch {
                    val start = geocodeAddressSuspend(context, fromText)
                    val end = geocodeAddressSuspend(context, toText)
                    if (start != null && end != null) {
                        saveToHistory(fromText)
                        saveToHistory(toText)
                        onValidate(start, end)
                    } else {
                        Toast.makeText(context, "Adresses non reconnues", Toast.LENGTH_SHORT).show()
                    }
                }
            },
            modifier = Modifier.fillMaxWidth(),
            enabled = fromText.isNotBlank() && toText.isNotBlank()
        ) {
            Text("Afficher le trajet")
        }
    }
}

fun buildSuggestions(query: String, stops: List<StopFields>, history: List<String>): List<String> {
    if (query.isBlank()) return emptyList()

    val lowerQuery = query.lowercase()

    val stopMatches = stops
        .filter { it.stop_name.lowercase().contains(lowerQuery) }
        .map { it.stop_name }

    val historyMatches = history
        .filter { it.lowercase().contains(lowerQuery) }

    return (stopMatches + historyMatches).distinct().take(8)
}

@Composable
fun SuggestionList(
    suggestions: List<String>,
    onSelect: (String) -> Unit
) {
    if (suggestions.isNotEmpty()) {
        Column(
            Modifier
                .fillMaxWidth()
                .background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(8.dp))
                .padding(4.dp)
        ) {
            suggestions.forEach { suggestion ->
                Text(
                    text = suggestion,
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable { onSelect(suggestion) }
                        .padding(8.dp),
                    style = MaterialTheme.typography.bodyMedium
                )
            }
        }
    }
}