import { Checkbox, Slider, Text } from '@fluentui/react-components'
import BaseLayer from 'ol/layer/Base'
import Map from 'ol/Map'
import { useEffect, useState } from 'react'

interface MapLayersProps {
    map: Map | null
}

const MapLayers = ({
    map
}: MapLayersProps) => {
    return (
        <div style={{ display: 'flex', flexDirection: 'column' }}>
            {map?.getLayers().getArray() && map?.getLayers().getArray().map((layer, index) => (
                <LayerSetting key={index} index={index} layer={layer} />
            ))}
        </div>
    )
}

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 (
        <div style={{ display: 'flex', alignItems: 'center' }} key={`layer-${index}`}>
            <Checkbox
                checked={visible}
                onChange={(e) => setVisible(e.currentTarget.checked)}
            />
            <Slider
                width='100%'
                min={0}
                max={1}
                step={0.001}
                value={opacity}
                onChange={(_, data) => setOpacity(data.value)}
            />
            <Text truncate size={300} onClick={() => { console.log(layer.getLayerState()) }}>
                {layer.get('name')}
            </Text>
        </div>
    )
}

export default MapLayers