import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui';
import { t } from 'i18next';

const ResendOtpButton = ({ onResendClick, resendOTP, blockedResendOTP }) => {
  const [timer, setTimer] = useState(60);

  useEffect(() => {
    let interval;

    if (timer > 0) {
      interval = setInterval(() => {
        setTimer((prevTimer) => prevTimer - 1);
      }, 1000);
    }

    return () => {
      clearInterval(interval);
    };
  }, [timer]);

  useEffect(() => {
    if (resendOTP) {
      setTimer(60);
    }
  }, [resendOTP]);

  return (
    <>
      <div className="flex justify-end gap-2">
        {blockedResendOTP ? (
          <Button
            type="button"
            variant="plain"
            aria-label={t('RESEND_OTP')}
            title={t('YOU_ARE_BLOCKED')}
            size="sm"
            className="flex justify-end gap-2"
            disabled={blockedResendOTP}
          >
            {t('RESEND_OTP')}
          </Button>
        ) : (
          <Button
            type="button"
            variant="plain"
            aria-label={t('RESEND_OTP')}
            title={t('RESEND_OTP')}
            size="sm"
            className="flex justify-end gap-2"
            onClick={onResendClick} // Call your OTP sending logic here
            loading={resendOTP}
            disabled={timer > 0}
          >
            {timer > 0 ? t(`RESEND_IN`) + ' ' + timer + 's' : t('RESEND_OTP')}
          </Button>
        )}
      </div>
    </>
  );
};

export default ResendOtpButton;
