import { debounce } from 'lodash';
import React, { PureComponent } from 'react';
import {
  Slider,
  StyleSheet,
  Text,
  View,
  ViewStyle,
} from 'react-native';

interface Props {
  distance: number;
  disabled: boolean;
  style?: ViewStyle;
  sliderSecondaryColor: string;
  sliderPrimaryColor?: string;
  onChange: (value: number) => void;
}

export class CustomSlider extends PureComponent<Props, { distance: number }> {

  state = { distance: this.props.distance };

  onValueChange = debounce(this.props.onChange, 200);

  componentWillReceiveProps({ distance }: Props) {
    if (this.state.distance !== distance) {
      this.setState({ distance });
    }
  }

  onChange = (distance) => {
    this.setState({ distance });
    this.onValueChange(distance);
  }

  render() {
    const { disabled, sliderPrimaryColor, sliderSecondaryColor, style } = this.props;
    const distance = this.state.distance;
    return !disabled && (
      <View style={[styles.container, style]}>
        <Slider
          disabled={disabled}
          style={styles.slider}
          step={distance < 20 ? 1 : 2}
          minimumValue={1}
          maximumValue={100}
          value={distance}
          thumbTintColor={sliderPrimaryColor || 'white'}
          maximumTrackTintColor={sliderSecondaryColor}
          minimumTrackTintColor={sliderPrimaryColor || 'white'}
          onValueChange={this.onChange}
          onSlidingComplete={null}
        />
        <Text style={[styles.text, sliderPrimaryColor && { color: sliderPrimaryColor }]}>
          {
            distance < 100 ?
              `Do ${distance} km`
              : 'Wszystko'
          }

        </Text>
      </View>
    );
  }
}

export { CustomSlider as Slider };

const styles = StyleSheet.create({
  container: {
    paddingVertical: 16,
    flexDirection: 'row',
  },
  slider: {
    flex: 1,
  },
  text: {
    color: 'white',
    marginRight: 16,
    fontWeight: '600',
  },
});
