import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react';
import { __ } from '@wordpress/i18n';
import { useNavigate, useParams } from 'react-router-dom';
import { is, isEmpty, isNil, pathOr } from 'ramda';
import { wrap } from 'object-path-immutable';
import { klona } from 'klona';
import { useForm } from 'react-hook-form';

// store
import { storeSet, useStoreValue } from '../../store';

// api
import AmendmentsService from '../../service/amendments-service';

// tools
import set404FromErrorResponse from '../../helpers/set404FromErrorResponse';
import getBandoLabel from '../../helpers/getBandoLabel';
import getDateFromISOstring from '../../helpers/getDateFromISOstring';
import getEmailTemplateForSoccorso from '../../helpers/getStrippedHtmlBodyTags';

// components
import { Button } from 'primereact/button';
import BlockingOverlay from '../../components/BlockingOverlay';
import { Toast } from 'primereact/toast';
import { classNames } from 'primereact/utils';
import { Dialog } from 'primereact/dialog';
import FormField from '../../components/FormField';
import { Editor } from 'primereact/editor';
import { InputNumber } from 'primereact/inputnumber';
import { Checkbox } from 'primereact/checkbox';
import { InputSwitch } from 'primereact/inputswitch';
import { FileUpload } from 'primereact/fileupload';
import { Skeleton } from 'primereact/skeleton';
import SoccorsoComunications from './components/SoccorsoComunications';
import SoccorsoResendEmails from './components/SoccorsoResendEmails';

import { amendmentRequestedDocs, defaultMaxFileSize, mimeTypes } from '../../configData';
import getFormatedFileSizeText from '../../helpers/getFormatedFileSizeText';

const SoccorsoEditPreInstructor = () => {
    const isAsyncRequest = useStoreValue('isAsyncRequest');
    const { id, amendmentId } = useParams();
    const navigate = useNavigate();
    const [data, setData] = useState({});
    const [isVisibleCloseAmendDialog, setIsVisibleCloseAmendDialog] = useState(false);
    const [isVisibleExtendTimeDialog, setIsVisibleExtendTimeDialog] = useState(false);
    const [extendedTime, setExtendedTime] = useState(3);
    const [isLoadingExtendingTime, setIsLoadingExtendingTime] = useState(false);
    const [isLoadingReminding, setIsLoadingReminding] = useState(false);
    const [internalNote, setInternalNote] = useState('');
    const toast = useRef(null);
    const [formInitialData, setFormInitialData] = useState({});
    const [draftFormData, setDraftFormData] = useState({});
    const draftFilesRef = useRef(null);
    const [isVisibleDeleteDraftDialog, setIsVisibleDeleteDraftDialog] = useState(false);
    const emailSendResponse = pathOr([], ['emailSendResponse'], data);
    const {
        control,
        handleSubmit,
        formState: { errors },
        setValue,
        register,
        trigger,
        getValues
    } = useForm({
        defaultValues: useMemo(() => {
            return formInitialData;
        }, [formInitialData]), mode: 'onChange'
    });

    const goToEvaluationPage = () => {
        navigate(`/domande/${id}`);
    }

    const getCallback = (data) => {
        if (data.status === 'SUCCESS') {
            setData(getFormattedData(data.data));
            if (data.data.status === 'DRAFT') {
                setDraftFormData({
                    formFields: data.data.formFields || [],
                    responseDays: data.data.responseDays || 10,
                    note: data.data.note || '',
                    isSendNotification: data.data.isSendNotification ?? true,
                    isSendEmail: data.data.isSendEmail ?? true,
                });
            } else {
                let formDataInitial = (data.data.applicationFormFields || []).reduce((acc, cur) => {
                    if (cur.fieldValue) {
                        acc[cur.fieldId] = cur.fieldValue;
                    }
                    return acc;
                }, {});
                formDataInitial = {
                    ...formDataInitial,
                    amendmentDocuments: data.data.amendmentDocuments
                }
                setFormInitialData(formDataInitial);
            }
        }
        storeSet('unsetAsyncRequest');
    }

    const errGetCallback = (data) => {
        if (toast.current && data.message) {
            toast.current.show({
                severity: 'error',
                summary: '',
                detail: data.message
            });
        }
        set404FromErrorResponse(data);
        storeSet('unsetAsyncRequest');
    }

    const getFormattedData = (data) => {
        data.startDate = is(String, data.startDate) ? new Date(data.startDate) : (data.startDate ? data.startDate : '');
        data.expirationDate = is(String, data.expirationDate) ? new Date(data.expirationDate) : (data.expirationDate ? data.expirationDate : '');
        return data;
    };

    const renderHeader = () => {
        return (
            <span className="ql-formats">
                <button className="ql-bold" aria-label="Bold"></button>
                <button className="ql-italic" aria-label="Italic"></button>
                <button className="ql-underline" aria-label="Underline"></button>
                <button className="ql-link" aria-label="Link"></button>
                <button className="ql-list" value="ordered"></button>
                <button className="ql-header" value="2"></button>
                <button className="ql-header" value="3"></button>
                <button className="ql-blockquote"></button>
                <button className="ql-list" value="bullet"></button>
                <button className="ql-indent" value="-1"></button>
                <button className="ql-indent" value="+1"></button>
            </span>
        );
    };

    const header = renderHeader();

    const updateNewAmendmentData = (value, path) => {
        const newData = wrap(data).set(path, value).value();
        setData(newData);
    }

    const updateDraftValue = (value, path, maxValue) => {
        let finalValue = value;
        if (maxValue) {
            finalValue = value > maxValue ? maxValue : value;
        }
        const newData = wrap(draftFormData).set(path.split('.'), finalValue).value();
        setDraftFormData(newData);
    }

    const doSendDraft = () => {
        storeSet('setAsyncRequest');
        const payload = {
            note: draftFormData.note,
            responseDays: draftFormData.responseDays,
            isSendNotification: draftFormData.isSendNotification,
            isSendEmail: draftFormData.isSendEmail,
            formFields: draftFormData.formFields,
        };
        const formDataToSend = new FormData();
        const jsonBlob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
        formDataToSend.append('applicationAmendmentRequest', jsonBlob);
        if (draftFormData.files && draftFormData.files.length > 0) {
            draftFormData.files.forEach(file => formDataToSend.append('files', file));
        }
        AmendmentsService.updateDraftSoccorso(amendmentId, formDataToSend, updateDraftCallback, errUpdateDraftCallback);
    };

    const updateDraftCallback = (resp) => {
        if (resp.status === 'SUCCESS') {
            AmendmentsService.updateStatusSoccorso(amendmentId, sendStatusCallback, errSendStatusCallback);
        } else {
            storeSet('unsetAsyncRequest');
        }
    };

    const sendStatusCallback = (resp) => {
        if (resp.status === 'SUCCESS') {
            storeSet('setAsyncRequest');
            AmendmentsService.getSoccorsoById(getCallback, errGetCallback, [['id', parseInt(amendmentId)]]);
        } else {
            storeSet('unsetAsyncRequest');
        }
    };

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

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

    const doDeleteDraft = () => {
        storeSet('setAsyncRequest');
        AmendmentsService.deleteSoccorso(amendmentId, deleteCallback, errDeleteCallback);
    };

    const deleteCallback = (resp) => {
        if (resp.status === 'SUCCESS') {
            goToEvaluationPage();
        } else {
            storeSet('unsetAsyncRequest');
        }
    };

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

    const onSubmit = () => {
    };

    const doUpdateAmendment = (doClose = false) => {
        trigger();
        let formValues = klona(getValues());
        const newFormValues = Object.keys(formValues)
            .filter(v => v !== 'amendmentDocuments')
            .reduce((acc, cur) => {
                let fieldVal = formValues[cur];

                fieldVal = isEmpty(fieldVal) ? null : fieldVal;
                fieldVal = is(Array, fieldVal) ? fieldVal.map(o => o.id).join(',') : null;

                acc.push({
                    'fieldId': cur,
                    'fieldValue': fieldVal
                });
                return acc;
            }, []);
        const newAmendDocs = formValues.amendmentDocuments
            ? formValues.amendmentDocuments.map(o => o.id).join(',')
            : '';

        const submitData = {
            applicationFormFields: newFormValues,
            amendmentDocuments: newAmendDocs,
            amendmentNotes: data.amendmentNotes
        }

        storeSet('setAsyncRequest');
        AmendmentsService.updateSoccorso(
            amendmentId,
            submitData,
            (resp) => updateAmendmentCallback(resp, doClose),
            errUpdateAmendmentCallback
        );
    }

    const updateAmendmentCallback = (data, doClose = false) => {
        if (data.status === 'SUCCESS') {
            setData(getFormattedData(data.data));

            if (doClose) {
                const submitData = {
                    internalNote
                }
                storeSet('setAsyncRequest');
                AmendmentsService.closeSoccorso(amendmentId, submitData, closeAmendmentCallback, errCloseAmendmentCallback);
            } else {
                if (toast.current) {
                    toast.current.show({
                        severity: 'success',
                        summary: '',
                        detail: data.message
                    });
                }
                let formDataInitial = data.data.applicationFormFields.reduce((acc, cur) => {
                    if (cur.fieldValue) {
                        acc[cur.fieldId] = cur.fieldValue;
                    }
                    return acc;
                }, formInitialData);
                formDataInitial = {
                    ...formDataInitial,
                    amendmentDocuments: data.data.amendmentDocuments
                }
                setFormInitialData(formDataInitial);
            }
        }
        storeSet('unsetAsyncRequest');
    }

    const errUpdateAmendmentCallback = (data) => {
        if (toast.current && data.message) {
            toast.current.show({
                severity: 'error',
                summary: '',
                detail: data.message
            });
        }
        set404FromErrorResponse(data);
        storeSet('unsetAsyncRequest');
    }

    const openCloseAmendmentDialog = () => {
        setIsVisibleCloseAmendDialog(true);
    }

    const headerCloseAmendDialog = () => {
        return <span>{__('Chiudi Soccorso Istruttorio', 'gepafin')}</span>
    }

    const hideCloseAmendDialog = () => {
        setIsVisibleCloseAmendDialog(false);
    }

    const footerCloseAmendDialog = () => {
        return <div>
            <Button type="button" label={__('Annulla', 'gepafin')} onClick={hideCloseAmendDialog} outlined/>
            <Button
                type="button"
                disabled={isAsyncRequest || isEmpty(data.internalNotes)}
                label={__('Invia', 'gepafin')} onClick={doCloseAmendment}/>
        </div>
    }

    const doCloseAmendment = useCallback(() => {
        if (data.status === 'AWAITING') {
            const submitData = {
                internalNote
            }
            storeSet('setAsyncRequest');
            AmendmentsService.closeSoccorso(amendmentId, submitData, closeAmendmentCallback, errCloseAmendmentCallback);
        } else {
            doUpdateAmendment(true);
        }
    }, [data]);

    const closeAmendmentCallback = (data) => {
        if (data.status === 'SUCCESS') {
            if (toast.current) {
                toast.current.show({
                    severity: 'success',
                    summary: '',
                    detail: data.message
                });
            }
            if (data.data.status) {
                updateNewAmendmentData(data.data.status, ['status']);
                setIsVisibleCloseAmendDialog(false);
            }
        }
        storeSet('unsetAsyncRequest');
    }

    const errCloseAmendmentCallback = (data) => {
        if (toast.current && data.message) {
            toast.current.show({
                severity: 'error',
                summary: '',
                detail: data.message
            });
        }
        set404FromErrorResponse(data);
        storeSet('unsetAsyncRequest');
    }

    const headerExtendRespDialog = () => {
        return <span>{__('Estendi scadenza', 'gepafin')}</span>
    }

    const hideExtendRespDialog = () => {
        setIsVisibleExtendTimeDialog(false);
    }

    const footerExtendRespDialog = () => {
        return <div>
            <Button type="button" label={__('Annulla', 'gepafin')} onClick={hideExtendRespDialog} outlined/>
            <Button
                type="button"
                disabled={isLoadingExtendingTime || isEmpty(extendedTime)}
                label={__('Invia', 'gepafin')} onClick={doExtendTimeResponse}/>
        </div>
    }

    const openExtendResponseTimeDialog = () => {
        setIsVisibleExtendTimeDialog(true);
        setExtendedTime(3);
    }

    const doExtendTimeResponse = () => {
        setIsLoadingExtendingTime(true);
        AmendmentsService.extendSoccorso(amendmentId, extendedTime, extendCallback, errExtendCallback);
    }

    const extendCallback = (data) => {
        if (data.status === 'SUCCESS') {
            if (toast.current) {
                toast.current.show({
                    severity: 'success',
                    summary: '',
                    detail: data.message
                });
            }
            setIsVisibleExtendTimeDialog(false);
        }
        setIsLoadingExtendingTime(false);
    }

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

    const sendReminder = () => {
        setIsLoadingReminding(true);
        AmendmentsService.sendReminderForSoccorso(amendmentId, reminderCallback, errReminderCallback)
    }

    const reminderCallback = (data) => {
        if (data.status === 'SUCCESS') {
            if (toast.current) {
                toast.current.show({
                    severity: 'success',
                    summary: '',
                    detail: data.message
                });
            }
        }
        setIsLoadingReminding(false);
    }

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

    const updateEmailSendResponses = useCallback((newEmailData) => {
        const newData = wrap(data).set(['emailSendResponse'], newEmailData).value();
        setData(newData);
    }, [data]);

    useEffect(() => {
        if (formInitialData) {
            Object.keys(formInitialData).map(k => setValue(k, formInitialData[k]));
            trigger();
        }
    }, [formInitialData]);

    useEffect(() => {
        const parsedSoccorsoId = parseInt(amendmentId);
        const soccorsoEntityId = !isNaN(parsedSoccorsoId) ? parsedSoccorsoId : 0;

        AmendmentsService.getSoccorsoById(getCallback, errGetCallback, [['id', soccorsoEntityId]]);
    }, [amendmentId]);

    useEffect(() => {
        if (draftFilesRef.current && data.status === 'DRAFT') {
            const existingFiles = data.amendmentInitialDocuments || data.amendmentInitialDocument || [];
            draftFilesRef.current.setUploadedFiles(is(Array, existingFiles) ? existingFiles : []);
        }
    }, [data]);

    return (
        <div className="appPage">
            <div className="appPage__pageHeader">
                <h1>{__('Soccorso Istruttorio - Dettagli', 'gepafin')}</h1>
            </div>

            <div className="appPage__spacer"></div>
            <Toast ref={toast}/>
            <BlockingOverlay shouldDisplay={isAsyncRequest}/>

            <div className="appPageSection__row">
                <Button
                    type="button"
                    outlined
                    onClick={goToEvaluationPage}
                    label={__('Indietro', 'gepafin')}
                    icon="pi pi-arrow-left" iconPos="left"/>
            </div>

            <div className="appPage__spacer"></div>

            <div className="appPage__content">
                {!isAsyncRequest && !isEmpty(data) && data.status === 'DRAFT'
                    ? <>
                        <div className="appPageSection__withBorder column">
                            <p className="appPageSection__pMeta">
                                <span>{__('ID domanda', 'gepafin')}</span>
                                <span>{data.applicationId}</span>
                            </p>
                            <p className="appPageSection__pMeta">
                                <span>{__('Bando', 'gepafin')}</span>
                                <span>{data.callName}</span>
                            </p>
                            <p className="appPageSection__pMeta">
                                <span>{__('Referente Aziendale', 'gepafin')}</span>
                                <span>{data.beneficiaryName}</span>
                            </p>
                        </div>

                        <div className="appPageSection">
                            <div className="appPageSection columns">
                                <div>
                                    <h3>{__('Pec/Email', 'gepafin')}</h3>
                                    <div style={{ marginBottom: '30px' }} translate="no">
                                        <Editor
                                            value={draftFormData.note}
                                            placeholder={__('Digita qui il messagio', 'gepafin')}
                                            headerTemplate={header}
                                            onTextChange={(e) => updateDraftValue(e.htmlValue, 'note')}
                                            style={{ height: 80 * 3, width: '100%' }}
                                        />
                                    </div>

                                    <div style={{ marginBottom: '30px' }}>
                                        <div className="appForm__field">
                                            <label>{__('Allegati PEC', 'gepafin')}</label>
                                            <FileUpload
                                                ref={draftFilesRef}
                                                name="files[]"
                                                multiple
                                                accept={mimeTypes.map(o => o.code).join(',')}
                                                maxFileSize={defaultMaxFileSize}
                                                auto={false}
                                                customUpload={true}
                                                onSelect={(e) => {
                                                    updateDraftValue(e.files, 'files');
                                                }}
                                                onRemove={() => {
                                                    const updatedFiles = draftFilesRef.current.getFiles();
                                                    updateDraftValue(updatedFiles, 'files');
                                                }}
                                                headerTemplate={(options) => {
                                                    const { chooseButton } = options;
                                                    return (
                                                        <div className="p-fileupload-buttonbar"
                                                             data-pc-section="buttonbar">
                                                            {chooseButton}
                                                        </div>
                                                    );
                                                }}
                                                chooseOptions={{
                                                    label: __('Aggiungi i file', 'gepafin'),
                                                    icon: 'pi pi-plus'
                                                }}
                                                itemTemplate={(file, props) => {
                                                    if (file.id) {
                                                        return (
                                                            <div className="p-fileupload-row" data-pc-section="file">
                                                                <div data-pc-section="details"
                                                                     style={{
                                                                         display: 'flex',
                                                                         flexDirection: 'column',
                                                                         gap: '10px',
                                                                         textAlign: 'left'
                                                                     }}>
                                                                    <a className="p-fileupload-filename"
                                                                       href={file.filePath}
                                                                       target="_blank"
                                                                       rel="noreferrer">
                                                                        {file.name}
                                                                    </a>
                                                                </div>
                                                            </div>
                                                        );
                                                    }
                                                    return (
                                                        <div className="p-fileupload-row" data-pc-section="file">
                                                            <div data-pc-section="details"
                                                                 style={{
                                                                     display: 'flex',
                                                                     flexDirection: 'column',
                                                                     gap: '10px',
                                                                     textAlign: 'left'
                                                                 }}>
                                                                <div className="p-fileupload-filename"
                                                                     data-pc-section="filename">
                                                                    {file.name}
                                                                </div>
                                                                <span
                                                                    data-pc-section="filesize">{getFormatedFileSizeText(file.size)}</span>
                                                            </div>
                                                            <div data-pc-section="actions">
                                                                <Button
                                                                    type="button"
                                                                    icon="pi pi-times"
                                                                    className="p-button-rounded p-button-danger p-button-text"
                                                                    onClick={() => props.onRemove()}
                                                                />
                                                            </div>
                                                        </div>
                                                    );
                                                }}
                                                emptyTemplate={<p className="m-0">{__('Trascina i file qua')}</p>}
                                            />
                                        </div>
                                    </div>

                                    <h3>{__('Tempo per la Risposta (giorni)', 'gepafin')}</h3>
                                    <div style={{ marginBottom: '30px' }}>
                                        <InputNumber
                                            keyfilter="int"
                                            value={draftFormData.responseDays}
                                            showButtons
                                            onChange={(e) => updateDraftValue(e.value, 'responseDays', 9999)}/>
                                    </div>

                                    <h3>{__('Notifica', 'gepafin')}</h3>
                                    <div className="appPageSection__withBorder grey">
                                        <div className="appForm__field row">
                                            <InputSwitch
                                                inputId="draft_notify_email"
                                                checked={draftFormData.isSendEmail}
                                                onChange={(e) => updateDraftValue(e.value, 'isSendEmail')}/>
                                            <label
                                                htmlFor="draft_notify_email">{__('Notifiche Email', 'gepafin')}</label>
                                        </div>
                                        <div className="appForm__field row">
                                            <InputSwitch
                                                inputId="draft_notify_push"
                                                checked={draftFormData.isSendNotification}
                                                onChange={(e) => updateDraftValue(e.value, 'isSendNotification')}/>
                                            <label
                                                htmlFor="draft_notify_push">{__('Notifiche Push', 'gepafin')}</label>
                                        </div>
                                    </div>
                                </div>
                                {draftFormData.formFields && !isEmpty(draftFormData.formFields)
                                    ? <div>
                                        <h3>{__('Documenti da Integrare', 'gepafin')}</h3>
                                        <div className="appPageSection__withBorder grey">
                                            <div className="appPageSection__checklist">
                                                {draftFormData.formFields.map((o, i) => <div key={o.fieldId}>
                                                    <Checkbox
                                                        inputId={`draft_checklist_${o.fieldId}`}
                                                        onChange={(e) => updateDraftValue(
                                                            e.checked,
                                                            `formFields.${i}.selected`
                                                        )}
                                                        checked={o.selected}/>
                                                    <label
                                                        htmlFor={`draft_checklist_${o.fieldId}`}>{o.label}</label>
                                                </div>)}
                                            </div>
                                        </div>
                                    </div>
                                    : null}
                            </div>
                        </div>

                        <div className="appPageSection__message warning">
                            <i className="pi pi-exclamation-triangle"></i>
                            <span
                                className="summary">{__('Attenzione', 'gepafin')}</span>
                            <span>{__('L\'invio della richiesta di integrazione sospenderà il termine di valutazione della domanda.', 'gepafin')}</span>
                        </div>

                        <div className="appPageSection__hr">
                            <span>{__('Azioni', 'gepafin')}</span>
                        </div>

                        <div className="appPageSection">
                            <div className="appPageSection__actions">
                                <Button
                                    type="button"
                                    outlined
                                    onClick={() => setIsVisibleDeleteDraftDialog(true)}
                                    label={__('Annulla', 'gepafin')}
                                    icon="pi pi-times" iconPos="right"/>
                                <Button
                                    type="button"
                                    onClick={doSendDraft}
                                    disabled={isAsyncRequest}
                                    label={__('Invia richiesta', 'gepafin')}
                                    icon="pi pi-check" iconPos="right"/>
                            </div>
                        </div>
                    </>
                    : !isAsyncRequest && !isEmpty(data)
                        ? <>
                <div className="appPageSection__withBorder columns">
                    <p className="appPageSection__pMeta">
                        <span>{__('ID domanda', 'gepafin')}</span>
                        <span>{data.applicationId}</span>
                    </p>
                    <p className="appPageSection__pMeta">
                        <span>{__('Bando', 'gepafin')}</span>
                        <span>{data.callName}</span>
                    </p>
                    <p className="appPageSection__pMeta">
                        <span>{__('Referente Aziendale', 'gepafin')}</span>
                        <span>{data.beneficiaryName}</span>
                    </p>
                    <p className="appPageSection__pMeta">
                        <span>{__('Inizio', 'gepafin')}</span>
                        <span>{getDateFromISOstring(data.startDate)}</span>
                    </p>
                    <p className="appPageSection__pMeta">
                        <span>{__('Scadenza', 'gepafin')}</span>
                        <span>{getDateFromISOstring(data.expirationDate)}</span>
                    </p>
                    <p className="appPageSection__pMeta">
                        <span>{__('Stato', 'gepafin')}</span>
                        <span>{getBandoLabel(data.status)}</span>
                    </p>
                </div>

                <div className="appPageSection">
                    <h2>{__('Dettagli richiesta', 'gepafin')}</h2>
                    <h3>{__('Note e spiegazioni', 'gepafin')}</h3>
                    <div
                        className="appPageSection__emailTemplate">{getEmailTemplateForSoccorso(data.emailTemplate, data.note)}</div>
                </div>

                {data.amendmentInitialDocument && is(Array, data.amendmentInitialDocument)
                    ? <div className="appPageSection">
                        <h3>{__('Documenti da PEC', 'gepafin')}</h3>
                        <ol className="appPageSection__list">
                            {data.amendmentInitialDocument.map((o, i) => <li key={o.fieldId}>
                                <a href={o.filePath} target="_blank" rel="noreferrer">{o.name}</a>
                            </li>)}
                        </ol>
                    </div> : null}

                {(data.formFields && !isEmpty(data.formFields)) || (data.amendmentType === 'SPECIAL' && !isNil(data.amendmentDocumentType)
                && !isNil(amendmentRequestedDocs[data.amendmentDocumentType]))
                    ? <div className="appPageSection">
                        <h3>{__('Documenti richiesti', 'gepafin')}</h3>
                        <ol className="appPageSection__list">
                            {data.formFields && !isEmpty(data.formFields)
                                ? data.formFields.map((o, i) => <li key={o.fieldId}
                                                               style={{ flexDirection: 'row' }}>
                                <span>{o.label}</span>
                            </li>) : null}
                            {!isNil(amendmentRequestedDocs[data.amendmentDocumentType]) ?? !isNil(amendmentRequestedDocs[data.amendmentDocumentType].map)
                                ? amendmentRequestedDocs[data.amendmentDocumentType].map((v) => <li key={v}
                                                                                       style={{ flexDirection: 'row' }}>
                                <span>{v}</span>
                            </li>) : null}
                        </ol>
                    </div> : null}

                <div className="appPageSection">
                    <h2>{__('Comunicazioni', 'gepafin')}</h2>
                    <SoccorsoComunications amendmentId={amendmentId} soccorsoStatus={data.status}/>
                </div>

                {data.formFields && !isEmpty(data.formFields)
                    ? <div className="appPageSection">
                        <h2>{__('Documenti Ricevuti', 'gepafin')}</h2>

                        <form className="appForm" onSubmit={handleSubmit(onSubmit)}>
                            {data.formFields.map((o, i) => {
                                return <FormField
                                    key={o.fieldId}
                                    disabled={['CLOSE', 'AWAITING', 'EXPIRED'].includes(data.status)}
                                    type="fileupload"
                                    setDataFn={setValue}
                                    saveFormCallback={doUpdateAmendment}
                                    fieldName={o.fieldId}
                                    label={o.label}
                                    control={control}
                                    register={register}
                                    errors={errors}
                                    defaultValue={formInitialData[o.fieldId] ? formInitialData[o.fieldId] : []}
                                    accept={[]}
                                    source="AMENDMENT"
                                    sourceId={amendmentId}
                                    multiple={true}
                                />
                            })}
                        </form>
                    </div> : null}

                <div className="appPageSection">
                    <h2>{__('Documenti aggiuntivi', 'gepafin')}</h2>
                    <div className="appPageSection">
                        <h3>{__('Notes', 'gepafin')}</h3>
                        <div style={{ marginBottom: '30px', width: '100%', position: 'relative' }} translate="no">
                            <BlockingOverlay shouldDisplay={['CLOSE', 'AWAITING', 'EXPIRED'].includes(data.status)}/>
                            <Editor
                                value={data.amendmentNotes}
                                readOnly={['CLOSE', 'AWAITING', 'EXPIRED'].includes(data.status)}
                                placeholder={__('Digita qui il messagio', 'gepafin')}
                                headerTemplate={header}
                                onTextChange={(e) => updateNewAmendmentData(
                                    e.htmlValue,
                                    'amendmentNotes'
                                )}
                                style={{ height: 80 * 3, width: '100%' }}
                            />
                        </div>
                        <FormField
                            type="fileupload"
                            disabled={['CLOSE', 'AWAITING', 'EXPIRED'].includes(data.status)}
                            setDataFn={setValue}
                            saveFormCallback={doUpdateAmendment}
                            fieldName="amendmentDocuments"
                            label={__('I file', 'gepafin')}
                            control={control}
                            register={register}
                            errors={errors}
                            defaultValue={formInitialData.amendmentDocuments ? formInitialData.amendmentDocuments : []}
                            accept={[]}
                            source="amendment"
                            sourceId={amendmentId}
                            multiple={true}
                        />
                    </div>
                </div>

                <div className="appPage__spacer"></div>

                <div className="appPageSection__hr">
                    <span>{__('Azioni', 'gepafin')}</span>
                </div>

                <div className="appPageSection">
                    <div className="appPageSection__actions">
                        <Button
                            type="button"
                            onClick={sendReminder}
                            disabled={isLoadingReminding || ['CLOSE', 'EXPIRED'].includes(data.status)
                                || (!isNil(emailSendResponse) && !isEmpty(emailSendResponse))}
                            outlined
                            label={__('Invia Sollecito', 'gepafin')}
                            icon="pi pi-send"
                        />
                        <Button
                            type="button"
                            onClick={openExtendResponseTimeDialog}
                            disabled={isLoadingExtendingTime || ['CLOSE'].includes(data.status)}
                            outlined
                            label={__('Estendi Scadenza', 'gepafin')}
                            icon="pi pi-stopwatch"
                        />
                        <Button
                            type="button"
                            onClick={() => doUpdateAmendment()}
                            disabled={isAsyncRequest || ['CLOSE', 'AWAITING', 'EXPIRED'].includes(data.status)}
                            label={__('Salva bozza', 'gepafin')}
                            icon="pi pi-save" iconPos="right"/>
                        <Button
                            type="button"
                            onClick={openCloseAmendmentDialog}
                            disabled={isAsyncRequest || ['CLOSE', 'EXPIRED'].includes(data.status)}
                            label={__('Chiudi Soccorso Istruttorio', 'gepafin')}
                            icon="pi pi-times" iconPos="right"/>
                    </div>
                    <div className="appPageSection__actions">
                        <SoccorsoResendEmails
                            emailsData={emailSendResponse}
                            setDataEmailsSoccorso={updateEmailSendResponses}/>
                    </div>
                </div>
                        </>
                        : <>
                            <Skeleton width="20%" height="1rem" className="mb-2"></Skeleton>
                            <Skeleton width="100%" height="2rem" className="mb-8"></Skeleton>
                            <Skeleton width="20%" height="1rem" className="mb-2"></Skeleton>
                            <Skeleton width="100%" height="4rem" className="mb-8"></Skeleton>
                            <Skeleton width="20%" height="1rem" className="mb-2"></Skeleton>
                            <Skeleton width="100%" height="2rem" className="mb-8"></Skeleton>
                            <Skeleton width="20%" height="1rem" className="mb-2"></Skeleton>
                            <Skeleton width="100%" height="4rem"></Skeleton>
                        </>}

            </div>

            <Dialog
                visible={isVisibleExtendTimeDialog}
                modal
                header={headerExtendRespDialog}
                footer={footerExtendRespDialog}
                style={{ maxWidth: '600px', width: '100%' }}
                onHide={hideExtendRespDialog}>
                <div className="appForm__field">
                    <label
                        className={classNames({ 'p-error': isEmpty(extendedTime) })}>
                        {__('Giorni', 'gepafin')}*
                    </label>
                    <InputNumber
                        keyfilter="int"
                        disabled={['CLOSE'].includes(data.status)}
                        value={extendedTime}
                        showButtons
                        onChange={(e) => setExtendedTime(e.value)}/>
                </div>
            </Dialog>

            <Dialog
                visible={isVisibleCloseAmendDialog}
                modal
                header={headerCloseAmendDialog}
                footer={footerCloseAmendDialog}
                style={{ maxWidth: '600px', width: '100%' }}
                onHide={hideCloseAmendDialog}>
                <div className="appForm__field">
                    <label>{__('Motivazioni', 'gepafin')}</label>
                    <div style={{ position: 'relative' }} translate="no">
                        <BlockingOverlay shouldDisplay={data.status === 'CLOSE'}/>
                        <Editor
                            value={internalNote}
                            readOnly={['CLOSE', 'EXPIRED'].includes(data.status)}
                            placeholder={__('Digita qui il messagio', 'gepafin')}
                            headerTemplate={header}
                            onTextChange={(e) => setInternalNote(e.htmlValue)}
                            style={{ height: 80 * 3, width: '100%' }}
                        />
                    </div>
                </div>
            </Dialog>

            <Dialog
                visible={isVisibleDeleteDraftDialog}
                modal
                header={<span>{__('Elimina bozza', 'gepafin')}</span>}
                footer={<div>
                    <Button type="button" label={__('No', 'gepafin')} onClick={() => setIsVisibleDeleteDraftDialog(false)} outlined/>
                    <Button type="button" label={__('Sì, elimina', 'gepafin')} onClick={doDeleteDraft} severity="danger"/>
                </div>}
                style={{ maxWidth: '500px', width: '100%' }}
                onHide={() => setIsVisibleDeleteDraftDialog(false)}>
                <p>{__('Sei sicuro di voler eliminare questa bozza? L\'operazione non può essere annullata.', 'gepafin')}</p>
            </Dialog>
        </div>
    )

}

export default SoccorsoEditPreInstructor;
