package com.isidroid.ui.maps

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.icons.filled.Place
import androidx.compose.material.icons.outlined.MailOutline
import androidx.compose.material.icons.rounded.LocationOn
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.dp
import androidx.lifecycle.flowWithLifecycle
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.LatLng
import com.google.maps.android.clustering.ClusterManager
import com.google.maps.android.compose.GoogleMap
import com.google.maps.android.compose.MapProperties
import com.google.maps.android.compose.MapUiSettings
import com.google.maps.android.compose.MapsComposeExperimentalApi
import com.google.maps.android.compose.clustering.Clustering
import com.google.maps.android.compose.rememberCameraPositionState
import com.isidroid.ui.maps.data.mapper.transformToClusterItem
import com.isidroid.ui.maps.ext.findMapRadius
import com.isidroid.ui.maps.model.MapMarker
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged

@OptIn(MapsComposeExperimentalApi::class, FlowPreview::class)
@Composable
fun MapsComponent(
    lat: Double,
    lng: Double,
    mapMarkersStateFlow: StateFlow<List<MapMarker>>,
    onCameraMove: (lat: Double, lng: Double, radius: Int) -> Unit,
    moveCameraToMyLocation: () -> Unit,
    clickOnMarker: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    val cameraPositionState = rememberCameraPositionState { position = CameraPosition.fromLatLngZoom(LatLng(lat, lng), 16f) }
    val items = mapMarkersStateFlow.collectAsState()
    val stateFlow = remember { MutableStateFlow(LatLng(lat, lng)) }
    val lifecycleOwner = LocalLifecycleOwner.current
    val context = LocalContext.current

    LaunchedEffect(cameraPositionState) {
        snapshotFlow { cameraPositionState.position }
            .collect { stateFlow.emit(it.target) }
    }

    LaunchedEffect(lat, lng) {
        cameraPositionState.move(CameraUpdateFactory.newLatLng(LatLng(lat, lng)))
    }

    LaunchedEffect(stateFlow) {
        stateFlow
            .flowWithLifecycle(lifecycleOwner.lifecycle)
            .distinctUntilChanged()
            .debounce(1000L)
            .collect { newLatLng ->
                val radius = findMapRadius(cameraPositionState.projection?.visibleRegion?.latLngBounds)
                onCameraMove(newLatLng.latitude, newLatLng.longitude, radius)
            }
    }

    Box(modifier = Modifier.fillMaxSize()) {
        GoogleMap(
            modifier = modifier.fillMaxSize(),
            properties = MapProperties(isMyLocationEnabled = false),
            cameraPositionState = cameraPositionState,
            uiSettings = MapUiSettings(zoomControlsEnabled = true),
            onMapLoaded = {},
            onMapClick = {},
            onMyLocationClick = {},
        ) {
            val parkMarkers = items.value.map { it.transformToClusterItem() }

            Clustering(
                items = parkMarkers,
                onClusterItemClick = {
                    clickOnMarker(it.id)
                    true
                },
                onClusterClick = {
                    cameraPositionState.move(CameraUpdateFactory.zoomIn())
                    true
                },
                onClusterItemInfoWindowClick = {},
                clusterItemContent = {
                    if (it.imageVector != null)
                        Icon(it.imageVector, contentDescription = null)
                    else
                        Icon(
                            Icons.Default.Place,
                            contentDescription = null,
                            tint = Color.Red,
                            modifier = Modifier.scale(1.2f)
                        )
                }
            )
        }

        IconButton(
            onClick = { moveCameraToMyLocation() },
            modifier = Modifier
                .align(Alignment.BottomStart)
                .padding(bottom = 72.dp, start = 12.dp)
                .background(Color.Black.copy(alpha = .45f), CircleShape)
        ) {
            Icon(
                imageVector = Icons.Default.LocationOn,
                contentDescription = null,
                tint = Color.White,
                modifier = Modifier
            )
        }
    }
}


