import Button from '../../shared/buttons/button';
import { useSendSmsKeyMutation } from '../../../hooks/react-query/use-temp-user';
import { useTimer } from '../../../hooks/index/use-timer';
import { APIErrorType } from '../../../api';

export type ResendSmsKeyPropsType = {
  mobile: string;
  onError: (error: APIErrorType) => void;
  className?: string;
};

function ResendView({ mobile, onError, className }: ResendSmsKeyPropsType) {
  const { timeLeft, resetTimeLeft } = useTimer(DEFAULT_TIME_LEFT);
  const { mutate: sendSmsKeyRequest } = useSendSmsKeyMutation();

  async function resend() {
    await sendSmsKeyRequest(
      { mobile },
      {
        onSuccess: resetTimeLeft,
        onError: onError
      }
    );
  }

  return (
    <div data-testid='smskey-resend-view' className={className}>
      {timeLeft > 0 ? (
        <p>
          <span>زمان انتظار برای ارسال مجدد: </span>
          <span>{timeLeft}</span>
          <span> ثانیه</span>
        </p>
      ) : (
        <Button
          outline
          color='yellow'
          disabled={timeLeft > 0}
          content='ارسال مجدد کد'
          onClick={resend}
          className='mx-auto'
        />
      )}
    </div>
  );
}

export const DEFAULT_TIME_LEFT = 60;

export default ResendView;
