import {Button} from "@mui/material";
import {useTranslations} from "next-intl";
import {useEffect} from "react";
import {LOGIN, SEND_OTP_TOKEN} from "../data/apiRoutes";
import {useDirection, useRequest} from "@witel/webapp-builder";

const ResendToken = ({initialTimerValue, timer, setTimer, PhoneNumber, disabled}) => {
    const t = useTranslations();
    const {directionApp} = useDirection();
    const requestServer = useRequest();
    // Countdown Timer
    useEffect(() => {
        let interval;
        if (timer > 0) {
            interval = setInterval(() => {
                setTimer((prevTimer) => prevTimer - 1);
            }, 1000);
        } else {
            clearInterval(interval);
        }

        return () => clearInterval(interval);
    }, [timer]);
    // End Countdown Timer

    // Handle Resend Token
    const handleResendClick = () => {
        if (timer != 0) return;
        requestServer(SEND_OTP_TOKEN, "post", {
            auth: false, data: {
                phone_number: PhoneNumber,
            }
        })
            .then(function (response) {
                setTimer(initialTimerValue);
            }).catch(function (error) {
        });
    };
    // End Handle Resend Token

    return (
        <>
            {timer > 0 ? (
                <Button
                    color="success"
                    disabled
                    sx={{width: "auto", alignSelf: "center", mt: 0}}
                    onClick={handleResendClick}
                >
                    {t("Resend_code_in")} {timer} {" "}
                    {t("seconds_later")}
                </Button>
            ) : (
                <Button
                    color="success"
                    sx={{width: "120px", alignSelf: "center", mt: 0}}
                    disabled={disabled}
                    onClick={handleResendClick}
                >
                    {t("resend_code")}
                </Button>
            )}
        </>
    );
};

export default ResendToken;

//////****** usage document ******/////////
// 1.) use <ResendToken /> component inside your page
// 2.) list of props that you need to send is down below
// 2.1) initialTimerValue **** Delay Time For Sending Token
// 2.2) timer **** Timer Of Resending Token
// 2.3) setTimer **** Set Timer Of Resend (note: every places in your components if you are requesting for getting token you should use this prop like this setTimer(initialTimerValue) )
// 2.4) PhoneNumber **** Phone Number That Should Recive Token
