package com.isidroid.ui.maps

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.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.graphics.Color
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.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

    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 = false   ),
            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 = {},
            )
        }

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


