import { Checkbox, Flex, NavLink, Slider, Stack } from '@mantine/core'
import BaseLayer from 'ol/layer/Base'
import Map from 'ol/Map'
import React, { useEffect, useState } from 'react'

interface MapLayersProps {
    map: React.MutableRefObject<Map | null>
}

const MapLayers = ({
    map
}: MapLayersProps) => {
    return (
        <Stack gap='0'>
            {map.current?.getLayers().getArray() && map.current?.getLayers().getArray().map((layer, index) => (
                <LayerSetting key={index} index={index} layer={layer} />
            ))}
        </Stack>
    )
}

interface LayerSettingProps {
    index: number;
    layer: BaseLayer;
}

const LayerSetting = ({
    index,
    layer
}: LayerSettingProps) => {
    const [opacity, setOpacity] = useState(layer.getOpacity())
    const [visible, setVisible] = useState(layer.getLayerState().visible)

    useEffect(() => {
        layer.setVisible(visible)
    }, [visible, layer])

    useEffect(() => {
        layer.setOpacity(opacity)
    }, [opacity, layer])

    return (
        <Flex key={`layer-${index}`} gap='xs' align='center'>
            <Checkbox
                checked={visible}
                onChange={(e) => setVisible(e.currentTarget.checked)}
            />
            <Slider
                w='100%'
                min={0}
                max={1}
                step={0.001}
                value={opacity}
                onChange={(value) => setOpacity(value)}
            />
            <NavLink p={0} label={layer.get('name')} onClick={() => { console.log(layer.getLayerState()) }} />
        </Flex>
    )
}

export default MapLayers