import React, { FunctionComponent, useEffect, useState } from 'react';
import { StyleSheet, Text, TextStyle } from 'react-native';
interface IProps {
  startTime?: number;
  style?: TextStyle;
}

export const Timer: FunctionComponent<IProps> = ({
  startTime = Date.now(),
  style,
}) => {
  let elapsedTimeInSeconds = (Date.now() - startTime) / 1000;
  const [, setDummy] = useState(elapsedTimeInSeconds);
  useEffect(() => {
    const intervalHandle = setInterval(() => {
      setDummy(++elapsedTimeInSeconds); // this is to force rerendering the component
    }, 1000);
    return () => clearInterval(intervalHandle);
  }, [elapsedTimeInSeconds]);

  const date = new Date(0);
  date.setSeconds(elapsedTimeInSeconds);
  const formattedValue = date.toISOString().substr(11, 8);

  const mergedStyle = { ...styles.timer, ...style };

  return <Text style={mergedStyle}>{formattedValue}</Text>;
};

const styles = StyleSheet.create({
  timer: {
    textAlign: 'center',
  },
});
