import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { useTranslation } from 'react-i18next';

interface CountdownTimerProps {
  initialSeconds: number,
  onComplete?: Function
}

export interface CountdownTimerRef {
  handleStop: Function,
  handleStart: Function,
  handleReset: Function,
  isActive: boolean
}

const CountdownTimer = forwardRef<CountdownTimerRef, CountdownTimerProps>((props, ref) => {

  const { initialSeconds, onComplete } = props
  const { t } = useTranslation()
  const [seconds, setSeconds] = useState(initialSeconds);
  const [isActive, setIsActive] = useState(false);
  const [title, setTitle] = useState('Send verification code')

  useImperativeHandle(ref, () => ({
    handleStop,
    handleReset,
    handleStart,
    isActive
  }))

  const handleStop = () => {
    setIsActive(false);
    setTitle('Send verification code')
  };

  const handleStart = () => {
    if (isActive) return
    setSeconds(initialSeconds)
    setIsActive(true);
  };

  const handleReset = () => {
    setSeconds(initialSeconds);
    setIsActive(true);
  };

  useEffect(() => {
    let interval: any = null;

    if (isActive && seconds > 0) {
      interval = setInterval(() => {
        setSeconds(seconds => seconds - 1);
      }, 1000);
    } else {
      clearInterval(interval)
      seconds <= 0 && setTitle('Resend')
      setIsActive(false)
      // onComplete && onComplete(seconds)
    }

    return () => clearInterval(interval);
  }, [isActive, seconds, onComplete]);

  return (
    <div style={{ whiteSpace: 'pre-wrap' }}>{isActive ? <span className='fz-18 fw550'>{seconds}s</span> : t(title)}</div>
  );
});

export default CountdownTimer;
