import React, {Component, useEffect, useState} from 'react';
import {View, Text} from 'react-native';
import {showAlert, TYPE} from './DropdownAlert';
import I18n from '../helper/i18/i18n';
import {getFontXD} from '../Config/Functions';
import R from '../assets/R';

const CountDown = (props) => {
    const [count, setCount] = useState(300);

    useEffect(() => {
        setCount(300);
    }, [props.isReset]);

    useEffect(() => {
        if (count == 0) {
            if(props.autoRefress) {
                props.autoRefress()
            }
            if(!props.isFromSmartOTP) {
                showAlert(TYPE.ERROR, I18n.t('Notification'), I18n.t('Overtime'));
            }
        }
    }, [count]);

    useEffect(() => {
        if (count > 0) {
            const timer = setTimeout(() => {
                setCount(count - 1);
                if(props.updateProgress) {
                    props.updateProgress(count)
                }
            }, 1000);
            return () => clearTimeout(timer);
        }
    });

    const secondToString = (count) => {
        const temp = count % 60;
        return temp < 10 ? `0${temp}` : temp;
    };

    return (
        props.isFromSmartOTP ?
            <Text
                style={{
                    color: R.colors.red2,
                    fontSize: getFontXD(39),
                }}>
                0{parseInt(count / 60)}:{secondToString(count)}
            </Text>
            :
            <View>
                <Text
                    style={{
                        color: '#A2A2A2',
                        fontStyle: 'italic',
                        fontSize: getFontXD(42),
                    }}>
                    0{parseInt(count / 60)}:{secondToString(count)}
                </Text>
            </View>
    );
};

export default CountDown;
