import { Button, Drawer, DrawerBody, DrawerHeader, Dropdown, Field, Link, Option, Text } from '@fluentui/react-components'
import { ArrowLeft24Regular } from '@fluentui/react-icons'
import { setSelectedDistrict, setSelectedRegion, setSelectedYear, useObjectsStore } from '../../../store/objects'
import { useMapStore } from '../../../store/map'
import { fromExtent } from 'ol/geom/Polygon'
import { getDistrictData, getRegionData, setDistrictsData, useRegionsStore } from '../../../store/regions'
import { IconX } from '@tabler/icons-react'
import { IDistrict, IRegion } from '../../../interfaces/gis'
import { getFeatureByEntityId } from '../mapUtils'
import useSWR, { SWRConfiguration } from 'swr'
import { fetcher } from '../../../http/axiosInstanceNest'
import { BASE_URL } from '../../../constants'
import { schemas } from '../../../constants/map'

const swrOptions: SWRConfiguration = {
    revalidateOnFocus: false
}

const MapRegionSelect = ({
    map_id
}: {
    map_id: string
}) => {
    const { map, districtSelect, regionsLayer, regionSelect, districtsLayer } = useMapStore().id[map_id]
    const { selectedRegion, selectedYear, selectedDistrict } = useObjectsStore().id[map_id]
    const { regionsData } = useRegionsStore()

    const { data: districtsData } = useSWR(selectedRegion ? `/general/districts/?region_id=${selectedRegion}` : null, (url) => fetcher(url, BASE_URL.nest).then(res => {
        setDistrictsData(res)
        return res
    }), swrOptions)

    return (
        <Drawer style={{ position: 'absolute', width: '300px', height: '100%', inset: 0, zIndex: 1 }} open={!selectedRegion || (!!selectedRegion && !selectedYear)} type='inline'>
            {!!selectedRegion && !selectedYear &&
                <DrawerHeader style={{ flexDirection: 'row' }}>
                    <Button icon={<ArrowLeft24Regular />} appearance='subtle' onClick={() => {
                        if (selectedDistrict) {
                            setSelectedDistrict(map_id, null)
                            districtSelect.getFeatures().clear()
                            regionsLayer.setOpacity(1)
                        } else {
                            setSelectedRegion(map_id, null)
                            regionSelect.getFeatures().clear()

                            if (map) {
                                const extent = regionsLayer.getSource()?.getExtent()

                                if (extent) {
                                    map.getView().fit(fromExtent(extent), { duration: 100 })
                                    regionsLayer.setOpacity(1)
                                }
                            }
                        }
                    }} />

                    {selectedDistrict ?
                        <Text weight='bold' size={500}>{getDistrictData(selectedDistrict)?.name}</Text>
                        :
                        <Text weight='bold' size={500}>{selectedRegion && getRegionData(selectedRegion)?.name}</Text>}

                    <Button appearance='subtle' style={{ marginLeft: 'auto' }} icon={<IconX />} onClick={() => {
                        setSelectedYear(map_id, null)
                        setSelectedDistrict(map_id, null)
                        setSelectedRegion(map_id, null)

                        if (map) {
                            const extent = regionsLayer.getSource()?.getExtent()

                            if (extent) {
                                map.getView().fit(fromExtent(extent), { duration: 100 })
                                regionsLayer.setOpacity(1)
                            }
                        }
                    }} />
                </DrawerHeader>
            }

            {!!selectedRegion && !selectedYear ?
                <DrawerBody>
                    <div key={selectedRegion} style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                        {selectedDistrict ?
                            selectedRegion && Object.entries(getRegionData(selectedRegion) as IRegion).map(([key, value]) => (
                                <div key={key} style={{ display: 'flex', justifyContent: 'space-between' }}>
                                    <span>{key}</span>
                                    <span>{value}</span>
                                </div>
                            ))
                            :
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
                                <div>
                                    {selectedRegion && Object.entries(getRegionData(selectedRegion) as IRegion).map(([key, value]) => (
                                        <div key={key} style={{ display: 'flex', justifyContent: 'space-between' }}>
                                            <span>{key}</span>
                                            <span>{value}</span>
                                        </div>
                                    ))}
                                </div>

                                {districtsData && districtsData.map((district: IDistrict) => (
                                    <Link key={district.id} onClick={() => {
                                        setSelectedDistrict(map_id, district.id)
                                        map?.removeInteraction(districtSelect)
                                    }}
                                        onMouseEnter={() => {
                                            const feature = getFeatureByEntityId(district.id, districtsLayer)

                                            if (feature) {
                                                districtSelect.getFeatures().push(feature)
                                            }
                                        }}
                                        onMouseLeave={() => {
                                            districtSelect.getFeatures().clear()
                                        }}
                                    >{district.name}</Link>
                                ))}
                            </div>
                        }

                        {selectedDistrict &&
                            <Field label="Схема" >
                                <Dropdown
                                    style={{ minWidth: 'auto' }}
                                    value={selectedYear ? selectedYear.toString() : ""}
                                    selectedOptions={[selectedYear ? selectedYear.toString() : ""]}
                                    onOptionSelect={(_ev, data) => {
                                        if (data.optionValue) {
                                            setSelectedYear(map_id, Number(data.optionValue));
                                        } else {
                                            setSelectedYear(map_id, null);
                                        }
                                    }}
                                >
                                    {schemas.map((el) => (
                                        <Option key={el} value={el} text={el}>
                                            {el}
                                        </Option>
                                    ))}
                                </Dropdown>
                            </Field>
                        }
                    </div>
                </DrawerBody>
                :
                <DrawerBody>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
                        {regionsData && regionsData.map((region: IRegion) => (
                            <Link key={region.id} onClick={() => {
                                setSelectedRegion(map_id, region.id)
                                map?.removeInteraction(regionSelect)
                            }}
                                onMouseEnter={() => {
                                    const feature = getFeatureByEntityId(region.id, regionsLayer)

                                    if (feature) {
                                        regionSelect.getFeatures().push(feature)
                                    }
                                }}
                                onMouseLeave={() => {
                                    regionSelect.getFeatures().clear()
                                }}
                            >{region.name}</Link>
                        ))}
                    </div>
                </DrawerBody>
            }

        </Drawer>
    )
}

export default MapRegionSelect