import React, {useState, useCallback, useEffect} from 'react'
import {Slider, InputNumber} from 'antd'
import styled from 'styled-components'


const Container = styled.div`
    width: 100%;
    display: inline-flex;
`

const JumpControls = (props: any)=>{
    const {src, currIndex, setBookContextState, pagesToTurn} = props
    const [inputValue, setInputValue] = useState(currIndex)
    const [sliderValue, setSliderValue] = useState(currIndex)
    const onChange = useCallback(
        (value) => {
            
            if(value){
                const newCurrIndex = value -1
                
                if(newCurrIndex < src.length && newCurrIndex >=0){
                    setBookContextState({
                        currIndex: value - 1,
                        flagToReverse: value < inputValue
                    })
                }                
            }  
        },
        [inputValue, src.length, setBookContextState])

    useEffect(()=>{
        setInputValue(currIndex + 1)
    }, [currIndex])

    useEffect(() => {
        setSliderValue(inputValue)
    }, [inputValue])


    const sliderRestProps = ()=>{
        return sliderValue === inputValue? {}: {value: inputValue}
    }

    return <Container>
        <Slider
            style={{
                flexGrow: 1
            }}
            min={1}
            max={src.length}
            onAfterChange={onChange}
            step={pagesToTurn}
            defaultValue={typeof inputValue === 'number' ? inputValue : 1}
            {...sliderRestProps()}
        />
        
        <InputNumber
            className={"jump-control"}
            min={1}
            max={src.length}
            style={{ margin: '0 8px' }}
            value={inputValue}
            onChange={onChange}
        />
    </Container>
}

export default JumpControls
