import React from 'react'
import PropTypes from 'prop-types'
import Plot from 'react-plotly.js'
import cloneDeep from 'lodash.clonedeep'
import isEqual from 'lodash.isequal'
import moment from 'moment'
import ric from 'request-idle-callback'
import {scatterData, scatterLayout} from './plotly.config'

class StockTimeseriesChart extends React.Component {
    _canSetState = true

    /* Required for a patch fix on a known plotly issue */
    lastCalcData = []

    /* A queue of intraday requests so we don't request for the same dataset
     * while one is resolving.
     */
    intradayRequestQueue = []

    state = {
        data: [],
        layout: cloneDeep(scatterLayout),
        selectedRange: [],
    }

    static getDerivedStateFromProps(nextProps) {
        return {
            data: [
                {
                    ...scatterData,
                    text: nextProps.timeseries && nextProps.timeseries.currency,
                    x: nextProps.timeseries && nextProps.timeseries.x,
                    y: nextProps.timeseries && nextProps.timeseries.y,
                },
            ],
        }
    }

    get selectedRange() {
        if (!this.state.layout.xaxis.range) {
            return []
        }

        return [
            this.state.layout.xaxis.range[0],
            this.state.layout.xaxis.range[1],
        ]
    }

    componentDidMount() {
        if (!this.props.getIntradayTimeseries) {
            return
        }

        // Load the current month's timeseries data
        ric.requestIdleCallback(() => {
            const startDate = moment.utc().startOf('month').format('YYYY-MM')
            this.getIntradayTimeseries(startDate)
        })
    }

    shouldComponentUpdate(nextProps) {
        if (isEqual(this.props.timeseries, nextProps.timeseries)) {
            return false
        }

        return true
    }

    componentWillUnmount() {
        this._canSetState = false
    }

    getIntradayTimeseries = (startDate) => {
        if (
            !this.props.getIntradayTimeseries ||
            this.intradayRequestQueue.includes(startDate)
        ) {
            return
        }

        // Maintain a queue so that we don't fetch for the same intraday data
        this.intradayRequestQueue.push(startDate)
        const removeFromQueue = () => {
            this.intradayRequestQueue.splice(
                this.intradayRequestQueue.indexOf(startDate),
                1
            )
        }

        this.props
            .getIntradayTimeseries(startDate)
            .then(removeFromQueue)
            .catch(removeFromQueue)
    }

    onError = () => {
        if (!this.gd) {
            return
        }
        // Known issue with plotly when dragging & updating data values.
        // https://github.com/plotly/plotly.js/issues/2644
        // In an attempt to recover, we keep track of the last calcdata
        // on the graphDiv, restore it, & initiate a re-render
        this.gd.calcdata = this.gd.calcdata || this.lastCalcData
        this._canSetState && this.setState({layout: this.state.layout})
    }

    onInit = (figure, graphDiv) => {
        this.gd = graphDiv
    }

    onUpdate = ({layout}, graphDiv) => {
        this.lastCalcData = graphDiv.calcdata

        if (!layout.xaxis.range || !layout.xaxis.range.length) {
            return
        }

        const rangeStart = layout.xaxis.range[0]
        const rangeEnd = layout.xaxis.range[1]

        const rangeChanged =
            rangeStart !== this.state.selectedRange[0] ||
            rangeEnd !== this.state.selectedRange[1]

        if (!rangeChanged) {
            return
        }

        const isIntraday = moment(rangeStart)
            .add(7, 'days')
            .isSameOrAfter(moment(rangeEnd))

        if (isIntraday) {
            // NOTE: Current BE implementation will fetch a month's worth of intraday
            // data using the month specified in the startDate. Our data provider
            // stores intraday values for a year so we should only fetch for them
            // if the startDate falls within this year.

            // Fetch a month in advance to improve UX, this mitigates the effect
            // graphs changing as users pan to the past.
            const startDateMoment = moment
                .utc(rangeStart)
                .startOf('month')
                .subtract(1, 'month')
            const startDate = startDateMoment.format('YYYY-MM')
            const isWithinAYear = startDateMoment.isAfter(
                moment.utc().subtract(1, 'year')
            )

            isWithinAYear && this.getIntradayTimeseries(startDate)
        }

        // At the moment, Plotly mutates the layout state, thus we need to
        // keep track of the selectedRange in order to indentify diffs
        // between each update.
        this.setState({selectedRange: [...layout.xaxis.range]})
    }

    render() {
        const {className} = this.props

        return (
            <Plot
                className={className}
                data={this.state.data}
                layout={this.state.layout}
                onError={this.onError}
                onInitialized={this.onInit}
                onUpdate={this.onUpdate}
                useResizeHandler
            />
        )
    }
}

StockTimeseriesChart.propTypes = {
    className: PropTypes.string,
    getIntradayTimeseries: PropTypes.func,
    timeseries: PropTypes.shape({
        currency: PropTypes.string,
        x: PropTypes.array,
        y: PropTypes.array,
    }),
}

export default StockTimeseriesChart
