package com.aiosman.riderpro

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.google.android.gms.common.api.ApiException
import com.google.android.libraries.places.api.Places
import com.google.android.libraries.places.api.model.Place
import com.google.android.libraries.places.api.net.PlacesClient
import com.google.android.libraries.places.api.net.SearchByTextRequest

data class SearchPlaceAddressResult(
    val name: String,
    val address: String
)

@Composable
fun SelectLocationModal(onClose:() -> Unit,onSelectedLocation: (SearchPlaceAddressResult) -> Unit) {
    val context = LocalContext.current
    var queryString by remember { mutableStateOf("") }
    var searchPlaceAddressResults by remember {
        mutableStateOf<List<SearchPlaceAddressResult>>(
            emptyList()
        )
    }

    fun searchAddrWithGoogleMap(query: String) {
        val placesClient: PlacesClient = Places.createClient(context)
        val placeFields: List<Place.Field> =
            listOf(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS)
        val request = SearchByTextRequest.newInstance(query, placeFields)
        placesClient.searchByText(request)
            .addOnSuccessListener { response ->
                val place = response.places
                searchPlaceAddressResults = place.map {
                    SearchPlaceAddressResult(it.name ?: "", it.address ?: "")
                }

            }.addOnFailureListener { exception ->
                if (exception is ApiException) {
                    Log.e("SelectLocationModal", "Place not found: ${exception.statusCode}")
                }
            }
    }
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 24.dp)
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 10.dp)
        ) {
            Text(
                "Check In",
                fontWeight = FontWeight.Bold,
                modifier = Modifier.align(Alignment.Center),
                fontSize = 16.sp
            )
            Text(
                "Cancel",
                modifier = Modifier.align(Alignment.CenterEnd).clickable {
                    onClose()
                },
                fontSize = 16.sp
            )
        }
        LocationSearchTextInput(queryString, onQueryClick = {
            searchAddrWithGoogleMap(queryString)
        }) {
            queryString = it
        }
        LazyColumn(
            modifier = Modifier
                .weight(1f)
                .padding(top = 28.dp)
        ) {
            item {
                for (searchPlaceAddressResult in searchPlaceAddressResults) {
                    LocationItem(searchPlaceAddressResult) {
                        onSelectedLocation(searchPlaceAddressResult)
                    }
                }
            }
        }

    }
}

@Composable
fun LocationSearchTextInput(
    value: String,
    onQueryClick: () -> Unit,
    onValueChange: (String) -> Unit
) {
    val keyboardController = LocalSoftwareKeyboardController.current

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 16.dp)
            .clip(shape = RoundedCornerShape(16.dp))
            .background(Color(0xffF5F5F5))
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 12.dp),

            verticalAlignment = Alignment.CenterVertically
        ) {
            Image(
                painter = painterResource(id = R.drawable.rider_pro_search_location),
                contentDescription = "Search",
                modifier = Modifier
                    .size(24.dp)
            )
            Spacer(modifier = Modifier.width(8.dp))
            if (value.isEmpty()) {
                Text(
                    "search",
                    modifier = Modifier.padding(vertical = 16.dp),
                    color = Color(0xffA0A0A0)
                )
            }
            BasicTextField(
                value = value,
                onValueChange = onValueChange,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 16.dp),
                keyboardOptions = KeyboardOptions(
                    imeAction = ImeAction.Search
                ),
                keyboardActions = KeyboardActions(
                    onSearch = {
                        onQueryClick()
                        // hide keyboard
                        keyboardController?.hide()

                    }
                )

            )
        }

    }

}

@Composable
fun LocationItem(
    searchPlaceAddressResult: SearchPlaceAddressResult,
    onLocationItemClick: () -> Unit = {}
) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 16.dp)
            .clickable {
                onLocationItemClick()
            }
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Column(
                modifier = Modifier
                    .weight(1f)
                    .padding(end = 16.dp)
            ) {
                Text(searchPlaceAddressResult.name, fontWeight = FontWeight.Bold)
                Text(searchPlaceAddressResult.address, color = Color(0xFF9a9a9a))
            }
            Image(
                painter = painterResource(id = R.drawable.rider_pro_nav_next),
                contentDescription = "Next",
                modifier = Modifier.size(24.dp)
            )

        }
    }
}