import distanceInWordsStrict from 'date-fns/distance_in_words_strict';
import format from 'date-fns/format';
import React, { Component } from 'react';
import { Text } from 'react-native';
import { TextStyle } from 'react-native';
const plLocale = require('date-fns/locale/pl');

const DEFAULT_UPDATE_INTERVAL = 10000;

type Prefix = {
  past: string;
  future: string;
};

interface Props {
  timestamp: number;
  updateInterval?: number;
  style?: TextStyle;
  prefix?: Prefix;
}

interface State {
  time: string;
}

function formatDate(date: number) {
  const now = Date.now();
  const isFromLastDay = now - date < 1000 * 60 * 60 * 24;
  if (isFromLastDay) {
    return distanceInWordsStrict(now, date, { locale: plLocale, addSuffix: true });
  } else {
    return format(date, 'MM/DD HH:mm');
  }
}

function prefixDate(date: number, prefix: Prefix): string {
  const prefixKey = date < Date.now() ? 'past' : 'future';
  return `${prefix[prefixKey]} ${formatDate(date)}`;
}

export class RelativeTimestamp extends Component<Props, State> {
  timeUpdater: any;

  constructor(props: Props) {
    super(props);
    const { prefix, timestamp } = props;
    const time = prefix
      ? prefixDate(timestamp, prefix)
      : formatDate(timestamp);
    this.state = { time };
  }

  updateTime(timestamp: number) {
    const time = this.props.prefix
      ? prefixDate(timestamp, this.props.prefix)
      : formatDate(timestamp);

    this.setState({ time });
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.timestamp !== this.props.timestamp) {
      this.updateTime(nextProps.timestamp);
    }
  }

  componentDidMount() {
    const { updateInterval, timestamp } = this.props;
    this.timeUpdater = setInterval(() => {
      this.updateTime(timestamp);
    }, updateInterval || DEFAULT_UPDATE_INTERVAL);
  }

  componentWillUnmount() {
    clearInterval(this.timeUpdater);
  }

  render() {
    return (
      <Text style={this.props.style}>
        {this.state.time}
      </Text>
    );
  }
}
