import * as React from 'react';
import { StepContainer } from '../../models/stepContainer';
import { Colors } from '../../models/colors';

export interface ProgressBarProps {
	stepsContainer?: Array<StepContainer>;
	currentStepID?: number;
	palette?: Colors;
	automationName?: string;
	translator?: Function;
}

interface ProgressBarState {
	scrollMode: boolean;
}

type ProgressBarContainer = ProgressBarProps & {
	render: (currentStepId: number, scrollMode?: boolean) => JSX.Element;
	withScrollMode?: boolean;
};

class ProgressBar extends React.Component<ProgressBarContainer> {
	state = {
		scrollMode: false
	};

	componentDidMount() {
		if (this.props.withScrollMode) {
			window.addEventListener('scroll', this.handleScroll, { passive: true });
		}
	}

	componentWillUnmount() {
		if (this.props.withScrollMode) {
			window.removeEventListener('scroll', this.handleScroll);
		}
	}

	shouldComponentUpdate(nextProps: ProgressBarProps, nextState: ProgressBarState) {
		return this.state.scrollMode !== nextState.scrollMode;
	}

	handleScroll = (event: MouseEvent) => {
		this.setState({
			scrollMode: window.scrollY > 100
		});
	};

	render() {
		return this.props.render(this.props.currentStepID, this.state.scrollMode);
	}
}

const mapStateToProps = (state: any) => ({
	currentStepID: state.step.currentStepID
});

export default ProgressBar;
