import { useEffect, useState, useRef } from 'react';
import SiteRepository from '../../../repository/SiteRepository';
import { HabitatSVG } from '../HabitatSVG'

export default function ZoneSelector(props) {

    const [habitatImageObject, setHabitatImageObject] = useState({});
    const [segmentMapping, setSegmentMapping] = useState({});
    const [selectedZoneSegment, setZoneSegment] = useState(null);

    const getHabitatImage = () => {
        SiteRepository.getHabitatImage(props.filters.habitatImage).then(response => {
            if (response.status === 200) {
                const imageData = response.data
                setHabitatImageObject(imageData)
            }
        })
    }

    const getZones = () => {
        SiteRepository.getZones().then(response => {
            if (response.status === 200) {
                const zoneData = response.data
                let newSegmentMapping = {}
                zoneData.forEach(zone => {
                    newSegmentMapping[zone.related_svg_segment] = zone
                });
                setSegmentMapping(newSegmentMapping);
            }
        })
    }

    const setZoneOrRedirect = (zone) => {
        const redirectHabitat = zone && zone.redirect_habitat;

        // If there is a redirect habitat set then redirect otherwise set the zone as state
        const newFilterState = redirectHabitat ? { "habitat": { "id": redirectHabitat.id, "name": redirectHabitat.name } } : { "zone": zone };

        props.updateFilterState(newFilterState);
        props.setRedirectBack(Boolean(redirectHabitat));

        props.setNextDisabled(false);
    }

    useEffect(() => {
        // Retrieves the habitat image from the api if it's not loaded already
        Object.keys(habitatImageObject).length === 0 && getHabitatImage()

        // Retrieves the habitat image from the api if it's not loaded already
        Object.keys(segmentMapping).length === 0 && getZones()


    }, [props.filters.zone]);

    const selectZone = (element) => {
        if (['path', 'rect'].includes(element.tagName) && element.attributes.inkscapelabel && element.attributes.inkscapelabel.nodeValue) {
            if (selectedZoneSegment) {
                selectedZoneSegment.style['fill-opacity'] = 0;
            }

            setZoneSegment(element)
            element.style.fill = "#eeeeee"
            element.style['fill-opacity'] = 0.5;

            const zone = segmentMapping[element.attributes.inkscapelabel.nodeValue]
            setZoneOrRedirect(zone)
        }
    }

    return Object.keys(habitatImageObject).length > 0 ? (
        <div style={{ width: '100%' }}>
            <p>{habitatImageObject.name}</p>
            <div className="zone-selector-svg">
                <HabitatSVG onClick={(event) => selectZone(event.target)} name={habitatImageObject.image_filename} style={{ "height": 'auto', "width": "100%" }} />
            </div>
        </div>) : <div></div>
}