import React, { useRef, useState } from 'react';
import { pathOr } from 'ramda';

// tools
import set404FromErrorResponse from '../../../../helpers/set404FromErrorResponse';

// api
import EmailService from '../../../../service/email-service';

import { Toast } from 'primereact/toast';
import { Button } from 'primereact/button';

import { resendEmailLabelsByType } from '../../../../configData';
import { useStoreValue } from '../../../../store';

const SoccorsoResendEmails = ({ emailsData = [], setDataEmailsSoccorso }) => {
    const [isResendingRequest, setIsResendingRequest] = useState(false);
    const toast = useRef(null);
    const role = useStoreValue('getRole');
    const filtered = emailsData.filter(o => !o.isEmailSend);

    const resendEmail = (data) => {
        setIsResendingRequest(true);

        EmailService.emailResend(
            data.userActionId,
            (resp) => resendingCallback(resp, data.userActionId),
            errResendingCallback
        );
    }

    const resendingCallback = (resp, id) => {
        if (resp.status === 'SUCCESS') {
            if (toast.current && resp.message) {
                toast.current.show({
                    severity: 'success',
                    summary: '',
                    detail: resp.message
                });
            }
            setTimeout(() => {
                if (setDataEmailsSoccorso) {
                    const newEmailSendResponse = emailsData.map((o) => {
                        if (o.userActionId === id) {
                            o.isEmailSend = true;
                        }
                        return o;
                    });
                    setDataEmailsSoccorso(newEmailSendResponse);
                }
                setIsResendingRequest(false);
            }, 1500);
        }
    }

    const errResendingCallback = (resp) => {
        if (toast.current && resp.message) {
            toast.current.show({
                severity: 'error',
                summary: '',
                detail: resp.message
            });
        }
        set404FromErrorResponse(resp);
        setIsResendingRequest(false);
    }

    return (
        ['ROLE_SUPER_ADMIN', 'ROLE_INSTRUCTOR_MANAGER'].includes(role) && filtered.length > 0
            ? <>
                <Toast ref={toast}/>
                {filtered
                    .map(o => <Button
                        key={o.userActionId}
                        severity="warning"
                        type="button"
                        disabled={isResendingRequest}
                        onClick={() => resendEmail(o)}
                        label={pathOr('Re-inivia email', ['emailScenario'], resendEmailLabelsByType)}
                        icon="pi pi-send" iconPos="right"/>)}
            </> : null
    )
}

export default SoccorsoResendEmails;