import { useEffect, useState, useRef } from 'react';
import SampleBackground from '../../../assets/img/stepBackgrounds/step1.jpg';
import SiteRepository from '../../../repository/SiteRepository';


export default function ZoneSelector(props) {

    const [habitatImageObject, setHabitatImageObject] = useState({});
    const [habitatImageFile, setHabitatImageFile] = useState(SampleBackground);
    const [imageHeight, setImageHeight] = useState(0)
    const [selectedZoneSegment, setZoneSegment] = useState(null);
    const imageContainer = useRef(null)

    const getHabitatImage = (findAndSetImageHeightFunc) => {
        SiteRepository.getHabitatImage(props.filters.habitatImage).then(response => {
            if (response.status === 200) {
                const imageData = response.data
                setHabitatImageObject(imageData)
                const imageSrc = require(`../../../assets/img/habitats/${imageData.image_filename}`).default
                setHabitatImageFile(imageSrc)
                findAndSetImageHeightFunc(imageSrc)
            }
        })
    }

    const setZone = (zoneSegment) => {
        setZoneSegment(zoneSegment)
        props.setNextDisabled(false);
    }

    useEffect(() => {
        // Calculates the image ratio and uses this to calculate the height in pixels based on outer container width
        const findAndSetImageHeight = (imageSource) => {
            let img = new Image();
            img.src = imageSource;
            const newHeight = imageContainer.current ? imageContainer.current.clientWidth * (img.height / img.width) : 0;
            setImageHeight(newHeight);
        }

        // Retrieves the habitat image from the api if they are not loaded already
        Object.keys(habitatImageObject).length === 0 && getHabitatImage(findAndSetImageHeight)

        // Sets the image height such that the full image always displays on page resize
        window.addEventListener("resize", () => findAndSetImageHeight(habitatImageFile), false);

        // Temporarily bypass if there is no image available
        if (props.filters.zone || !props.filters.habitatImage) {
            setZone(props.filters.zone)
        }
    });


    const stepBackground = {
        backgroundImage: `url(${habitatImageFile})`,
        backgroundSize: '100% auto',
        backgroundRepeat: 'none',
        height: imageHeight,
        width: '100%',
        display: 'flex'
    }

    const selectZone = (zoneSegment) => {
        // Update the filters for the selected zone and enable the next button
        setZone(zoneSegment)
        props.updateFilterState({ "zone": zoneSegment.zone });
    };

    return (
        <div ref={imageContainer} style={{ width: '100%' }}>
            <p>{habitatImageObject && habitatImageObject.name}</p>
            {Object.keys(habitatImageObject).length === 0 ? (
                // Sample segment selector (temporary if no image is available)
                <div style={stepBackground}>
                    <div className='selectable-section' style={{ width: '50%', height: '100%' }}></div>
                    <div className='selectable-section' style={{ width: '20%', height: '100%' }}></div>
                    <div className='selectable-section' style={{ width: '30%', height: '100%' }}></div>
                </div>) :
                // Actual zone selector
                (<div style={stepBackground}>
                    {habitatImageObject && habitatImageObject.image_segments && Array.isArray(habitatImageObject.image_segments) && habitatImageObject.image_segments.map(segment =>
                        <div key={segment.id} onClick={() => { selectZone(segment) }} className={`selectable-section ${selectedZoneSegment === segment.zone ? 'selected-segment' : ''}`} style={{ width: `${segment.segment_percentage_width}%`, height: '100%' }}></div>
                    )}
                </div>
                )}
        </div>
    )
}
