import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { useNavigate, useParams } from 'react-router-dom';
import { is, isEmpty, isNil, sum, pathOr, head, pluck } from 'ramda';
import { klona } from 'klona';
import { wrap } from 'object-path-immutable';
import { useForm } from 'react-hook-form';
import { evaluate, isNaN } from 'mathjs';
import equal from 'fast-deep-equal';

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

// api
import ApplicationEvaluationService from '../../service/application-evaluation-service';
import AmendmentsService from '../../service/amendments-service';
import AppointmentService from '../../service/appointment-service';

// tools
import set404FromErrorResponse from '../../helpers/set404FromErrorResponse';
import {
    isCAP,
    isCodiceFiscale,
    isEmail,
    isEmailPEC,
    isIBAN,
    isMarcaDaBollo,
    isPIVA,
    isUrl, maxChecks, minChecks, nonEmptyTables
} from '../../helpers/validators';
import formatDateString from '../../helpers/formatDateString';
import getTokens from '../../helpers/getTokens';
import parseCommaDecimal from '../../helpers/parseCommaDecimal';
import renderWithDataVars from '../../helpers/renderWithDataVars';
import renderHtmlContent from '../../helpers/renderHtmlContent';
import getFormatedFileSizeText from '../../helpers/getFormatedFileSizeText';

// components
import { Skeleton } from 'primereact/skeleton';
import { Button } from 'primereact/button';
import { Tag } from 'primereact/tag';
import { Checkbox } from 'primereact/checkbox';
import { Editor } from 'primereact/editor';
import { InputNumber } from 'primereact/inputnumber';
import { Toast } from 'primereact/toast';
import { Dialog } from 'primereact/dialog';
import HelpIcon from '../../icons/HelpIcon';
import BlockingOverlay from '../../components/BlockingOverlay';
import { classNames } from 'primereact/utils';
import { InputTextarea } from 'primereact/inputtextarea';
import { InputText } from 'primereact/inputtext';
import { Dropdown } from 'primereact/dropdown';
import ListOfFiles from '../DomandaEditPreInstructor/components/ListOfFiles';
import EvaluationExtraFiles from '../DomandaEditPreInstructor/components/EvaluationExtraFiles';
import ApplicationInfo from '../DomandaEditPreInstructor/components/ApplicationInfo';
import ApplicationDownloadFiles from '../DomandaEditPreInstructor/components/ApplicationDownloadFiles';
import FormField from '../../components/FormField';
import SoccorsoResendEmails from '../SoccorsoEditPreInstructor/components/SoccorsoResendEmails';
import EvaluationReAdmit from '../DomandaEditPreInstructor/components/EvaluationReAdmit';
import { SplitButton } from 'primereact/splitbutton';
import { FileUpload } from 'primereact/fileupload';
import { defaultMaxFileSize, mimeTypes, rejectionReasons } from '../../configData';
import ArchiveDocument from '../DomandaEditPreInstructor/components/ArchiveDocument';

const APP_EVALUATION_FLOW_ID = process.env.REACT_APP_EVALUATION_FLOW_ID;
const APP_HUB_ID = process.env.REACT_APP_HUB_ID;

const DomandaEditInstructorManager = () => {
    const isAsyncRequest = useStoreValue('isAsyncRequest');
    const { id } = useParams();
    const navigate = useNavigate();
    const [data, setData] = useState({});
    const [isVisibleCriterionData, setIsVisibleCriterionData] = useState(0);
    const [criterionDataTitle, setCriterionDataTitle] = useState('');
    const [criterionDataContent, setCriterionDataContent] = useState('');
    const [isAdmissible, setIsAdmissible] = useState(false);
    const [connectedSoccorsoId, setConnectedSoccorsoId] = useState(0);
    const toast = useRef(null);
    const tecFinBtnRef = useRef(null);
    const [loading, setLoading] = useState(false);
    const [isVisibleCompleteDialog, setIsVisibleCompleteDialog] = useState(false);
    const [operationType, setOperationType] = useState('');
    const [finalDialogData, setFinalDialogData] = useState({
        motivation: ''
    });
    const finalDialogFilesRef = useRef(null);
    const [isVisibleAppointmentDialog, setIsVisibleAppointmentDialog] = useState(false);
    const [isVisiblePreTecEvalDialog, setIsVisiblePreTecEvalDialog] = useState(false);
    const [preTecEvalData, setPreTecEvalData] = useState({
        amendmentDocumentType: '',
        amount: 0,
        blueTongueField1: 0,
        blueTongueField2: 0
    });
    const [allFilesRated, setAllFilesRated] = useState(false);
    const [atLeastOneChecked, setAtLeastOneChecked] = useState(false);
    const [allChecksChecked, setAllChecksChecked] = useState(false);
    const [appointmentData, setAppointmentData] = useState({
        title: '',
        text: '',
        duration: 0,
        amount: 0
    });
    /*const [isVisibleContractForm, setIsVisibleContractForm] = useState(false);
    const [contractFormData, setContractFormData] = useState({
        subject: '',
        text: ''
    });
    const contractFormFilesRef = useRef(null);*/
    const [formData, setFormData] = useState([]);
    const [formId, setFormId] = useState(0);
    const [formInitialData, setFormInitialData] = useState(null);
    const emailSendResponse = pathOr([], ['emailSendResponse'], data);
    const {
        control,
        handleSubmit,
        formState: { errors },
        setValue,
        trigger,
        register,
        getValues,
        watch,
        reset
    } = useForm({
        defaultValues: useMemo(() => {
            return formInitialData ? formInitialData : {}
        }, [formInitialData]),
        mode: 'onChange'
    });
    const validationFns = {
        isPIVA,
        isCodiceFiscale,
        isCAP,
        isIBAN,
        isEmail,
        isEmailPEC,
        isUrl,
        isMarcaDaBollo,
        minChecks,
        maxChecks,
        nonEmptyTables
    }
    const values = getValues();
    const formValues = watch();

    const goToEvaluationsPage = () => {
        navigate('/mie-domande');
    }

    const updateFlagsForSoccorso = useCallback((data) => {
        let nonRatedFilesLength = 0;
        let nonRatedAmmendFilesLength = 0;

        if (data.files) {
            const nonRatedFiles = data.files
                .map(el => el.valid)
                .filter(v => isNil(v));
            nonRatedFilesLength = nonRatedFiles.length;
        }

        if (data.amendmentDetails) {
            const nonRatedFiles = data.amendmentDetails
                .map(el => el.valid)
                .filter(v => isNil(v));
            nonRatedAmmendFilesLength = nonRatedFiles.length;
        }

        setAllFilesRated(nonRatedFilesLength === 0 && nonRatedAmmendFilesLength === 0);

        if (data.evaluationVersion === 'V1') {
            if (data.checklist) {
                const checkedChecklistItems = data.checklist
                    .map(el => el.valid)
                    .filter(v => v);
                setAtLeastOneChecked(checkedChecklistItems.length > 0);
                setAllChecksChecked(checkedChecklistItems.length === data.checklist.length)
            }
        } else if (data.evaluationVersion === 'V2') {
            const minChecks = data.numberOfCheck;
            const formFieldsChecklist = formData
                .filter(o => head(o.settings.filter(s => s.name === 'isChecklistItem' && s.value)))
                .map(o => o.id);

            if (minChecks === 0) {
                setAtLeastOneChecked(true);
                setAllChecksChecked(true);
            } else if (formFieldsChecklist.length > minChecks) {
                const valuesTotal = formFieldsChecklist.map(v => formValues[v]);
                const valuesFirst = valuesTotal.toSpliced(minChecks);
                setAtLeastOneChecked(valuesFirst.filter(v => Boolean(v) === true).length === valuesFirst.length);
                setAllChecksChecked(valuesTotal.filter(v => Boolean(v) === true).length === valuesTotal.length);
            }
        }
    }, [formValues]);

    const doNewSoccorso = () => {
        if (connectedSoccorsoId !== 0) {
            navigate(`/mie-domande/${id}/soccorso/${connectedSoccorsoId}`);
        } else {
            doSaveDraft(navigateToNewSoccorso)
        }
    }

    const navigateToNewSoccorso = () => {
        navigate(`/mie-domande/${id}/aggiungi-soccorso/`);
    }

    const getVersion = (resp) => {
        if (resp.status === 'SUCCESS') {
            if (resp.data.evaluationVersion === 'V1') {
                storeSet('setAsyncRequest');
                ApplicationEvaluationService.getEvaluationByApplId(getCallback, errGetCallback, [
                    ['applicationId', resp.data.applicationId]
                ]);
            } else if (resp.data.evaluationVersion === 'V2') {
                storeSet('setAsyncRequest');
                ApplicationEvaluationService.getEvaluationV2ByApplId(getCallback, errGetCallback, [
                    ['applicationId', resp.data.applicationId]
                ]);
            }
        }
        storeSet('unsetAsyncRequest');
    }

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

    const getCallback = (resp) => {
        if (resp.status === 'SUCCESS') {
            setData(getFormattedData(resp.data));
            setFinalDialogData((prev) => ({ ...prev, motivation: resp.data.motivation }));
            updateFlagsForSoccorso(resp.data);

            if (resp.data.evaluationVersion === 'V2') {
                setFormData(resp.data.applicationEvaluationFormResponse.content);
                setFormId(resp.data.applicationEvaluationFormResponse.id);
                let formDataInitial = {};

                if (resp.data.applicationEvaluationFormResponse.formFields) {
                    const submitData = resp.data.applicationEvaluationFormResponse.formFields.map((o) => ({
                        fieldId: o.fieldId,
                        fieldValue: o.fieldValue
                    }));
                    formDataInitial = submitData.reduce((acc, cur) => {
                        if (cur.fieldValue) {
                            acc[cur.fieldId] = cur.fieldValue;
                        }
                        return acc;
                    }, formDataInitial);
                }

                reset();
                setFormInitialData(formDataInitial);
            }
        }
        storeSet('unsetAsyncRequest');
    }

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

    const getFormattedData = (data) => {
        data.submissionDate = is(String, data.submissionDate) ? new Date(data.submissionDate) : (data.submissionDate ? data.submissionDate : '');
        data.evaluationDate = is(String, data.evaluationDate) ? new Date(data.evaluationDate) : (data.evaluationDate ? data.evaluationDate : '');
        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 tecnicalEvalItems = [
        {
            label: __('Nessuna garanzia', 'gepafin'),
            icon: 'pi pi-pen-to-square',
            command: () => {
                setPreTecEvalData(prev => ({ ...prev, amendmentDocumentType: 'NESSUNA_GARANZIA' }));
                setIsVisiblePreTecEvalDialog(true);
            }
        },
        {
            label: __('Garanzia MCC', 'gepafin'),
            icon: 'pi pi-pen-to-square',
            command: () => {
                setPreTecEvalData(prev => ({ ...prev, amendmentDocumentType: 'GARANZIA_MCC' }));
                setIsVisiblePreTecEvalDialog(true);
            }
        },
        {
            label: __('Garanzia MCC Start-Up', 'gepafin'),
            icon: 'pi pi-pen-to-square',
            command: () => {
                setPreTecEvalData(prev => ({ ...prev, amendmentDocumentType: 'MCC_START_UP' }));
                setIsVisiblePreTecEvalDialog(true);
            }
        },
        {
            label: __('Altre garanzie (fideiussioni)', 'gepafin'),
            icon: 'pi pi-pen-to-square',
            command: () => {
                setPreTecEvalData(prev => ({ ...prev, amendmentDocumentType: 'ALTRE_GARANZIE' }));
                setIsVisiblePreTecEvalDialog(true);
            }
        },
        {
            label: __('Blue Tongue', 'gepafin'),
            icon: 'pi pi-pen-to-square',
            command: () => {
                setPreTecEvalData(prev => ({ ...prev, amendmentDocumentType: 'BLUE_TONGUE' }));
                setIsVisiblePreTecEvalDialog(true);
            }
        }
    ]

    const updateEvaluationValue = (value, path, maxValue = null) => {
        let finalValue = value;

        if (maxValue || maxValue === 0) {
            finalValue = value > maxValue ? maxValue : value;
        }

        const newData = wrap(data).set(path, finalValue).value();
        setData(newData);
        updateFlagsForSoccorso(newData);
    }

    const getTransformedSubmitData = () => {
        const formValues = getValues();
        const usedFieldsIds = pluck('id', formData);
        return Object.keys(formValues)
            .filter(v => usedFieldsIds.includes(v))
            .reduce((acc, cur) => {
                const formField = head(formData.filter(o => o.id === cur));
                let fieldVal = formValues[cur];

                if (formValues[cur] && formValues[cur].toISOString) {
                    fieldVal = formatDateString(formValues[cur]);
                }

                fieldVal = isEmpty(fieldVal) ? null : fieldVal;
                if (formField && formField.name === 'fileupload') {
                    fieldVal = is(Array, fieldVal) ? fieldVal.map(o => o.id).join(',') : null;
                }
                acc.push({
                    'fieldId': cur,
                    'fieldValue': fieldVal
                });
                return acc;
            }, []);
    }

    const doSaveDraft = useCallback((afterUpdateCallback = null, cfgModifier = {}) => {
        if (data.evaluationVersion === 'V1') {
            const submitData = {
                criteria: klona(data.criteria),
                checklist: klona(data.checklist),
                files: klona(data.files),
                evaluationDocument: klona(data.evaluationDocument.map(o => ({
                        ...o,
                        fileValue: o.fileValue && o.fileValue[0] ? o.fileValue[0].id : ''
                    })
                )),
                amendmentDetails: klona(data.amendmentDetails),
                note: data.note,
                ...cfgModifier
            };

            const formDataToSend = new FormData();
            const jsonBlob = new Blob([JSON.stringify(submitData)], {
                type: 'application/json'
            });
            formDataToSend.append('evaluationRequest', jsonBlob);

            ApplicationEvaluationService.updateEvaluation(
                data.assignedApplicationId,
                formDataToSend,
                (data) => updateCallback(data, afterUpdateCallback),
                errUpdateCallback
            );
        } else if (data.evaluationVersion === 'V2') {
            const newFormValues = getTransformedSubmitData();
            const submitData = {
                formFields: newFormValues,
                files: klona(data.files),
                evaluationDocument: klona(data.evaluationDocument.map(o => ({
                        ...o,
                        fileValue: o.fileValue[0] ? o.fileValue[0].id : ''
                    })
                )),
                amendmentDetails: klona(data.amendmentDetails),
                note: data.note,
                ...cfgModifier
            }

            const formDataToSend = new FormData();
            const jsonBlob = new Blob([JSON.stringify(submitData)], {
                type: 'application/json'
            });
            formDataToSend.append('applicationEvaluationFormRequestBean', jsonBlob);

            ApplicationEvaluationService.updateEvaluationV2(
                data.assignedApplicationId,
                formId,
                formDataToSend,
                (data) => updateCallback(data, afterUpdateCallback),
                errUpdateCallback
            );
        }
    }, [data]);

    /**
     *
     * @param data {object}
     * @param afterUpdateCallback {function}
     */
    const updateCallback = (data, afterUpdateCallback = null) => {
        if (data.status === 'SUCCESS') {
            setData(getFormattedData(data.data));
            if (toast.current) {
                toast.current.show({
                    severity: 'success',
                    summary: '',
                    detail: data.message
                });
            }
            if (afterUpdateCallback) {
                afterUpdateCallback();
            }
        }
        storeSet('unsetAsyncRequest');
    }

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

    const doApprove = useCallback(() => {
        if (data.evaluationVersion === 'V1') {
            const submitData = {
                applicationStatus: 'APPROVED',
                criteria: klona(data.criteria),
                checklist: klona(data.checklist),
                files: klona(data.files),
                note: data.note,
                motivation: finalDialogData.motivation,
                amountAccepted: finalDialogData.amount
            }

            const formDataToSend = new FormData();
            const jsonBlob = new Blob([JSON.stringify(submitData)], {
                type: 'application/json'
            });
            formDataToSend.append('evaluationRequest', jsonBlob);

            setLoading(true);
            setIsVisibleCompleteDialog(false);
            ApplicationEvaluationService.updateEvaluation(
                data.assignedApplicationId,
                formDataToSend,
                approveRejectCallback,
                errApproveRejectCallback
            );
        } else if (data.evaluationVersion === 'V2') {
            const newFormValues = getTransformedSubmitData();
            const submitData = {
                applicationStatus: 'APPROVED',
                formFields: newFormValues,
                files: klona(data.files),
                evaluationDocument: klona(data.evaluationDocument.map(o => ({
                        ...o,
                        fileValue: o.fileValue[0] ? o.fileValue[0].id : ''
                    })
                )),
                amendmentDetails: klona(data.amendmentDetails),
                note: data.note,
                motivation: finalDialogData.motivation,
                amountAccepted: finalDialogData.amount
            }

            const formDataToSend = new FormData();
            const jsonBlob = new Blob([JSON.stringify(submitData)], {
                type: 'application/json'
            });
            formDataToSend.append('applicationEvaluationFormRequestBean', jsonBlob);

            setLoading(true);
            setIsVisibleCompleteDialog(false);
            ApplicationEvaluationService.updateEvaluationV2(
                data.assignedApplicationId,
                formId,
                formDataToSend,
                approveRejectCallback,
                errApproveRejectCallback
            );
        }
    }, [data, finalDialogData]);

    const doReject = useCallback((newStatus) => {
        if (data.evaluationVersion === 'V1') {
            const submitData = {
                applicationStatus: newStatus,
                criteria: klona(data.criteria),
                checklist: klona(data.checklist),
                files: klona(data.files),
                note: data.note,
                motivation: finalDialogData.motivation,
                rejectedReason: finalDialogData.reason,
                rejectedReasonSubject: finalDialogData.subject
            }

            const formDataToSend = new FormData();
            const jsonBlob = new Blob([JSON.stringify(submitData)], {
                type: 'application/json'
            });
            formDataToSend.append('evaluationRequest', jsonBlob);

            if (finalDialogData.files && finalDialogData.files.length > 0) {
                finalDialogData.files.forEach((file) => {
                    formDataToSend.append('rejectedDocuments', file);
                });
            }

            setLoading(true);
            setIsVisibleCompleteDialog(false);
            ApplicationEvaluationService.updateEvaluation(
                data.assignedApplicationId,
                formDataToSend,
                approveRejectCallback,
                errApproveRejectCallback
            );
        } else if (data.evaluationVersion === 'V2') {
            const newFormValues = getTransformedSubmitData();
            const submitData = {
                applicationStatus: newStatus,
                formFields: newFormValues,
                files: klona(data.files),
                evaluationDocument: klona(data.evaluationDocument.map(o => ({
                        ...o,
                        fileValue: o.fileValue[0] ? o.fileValue[0].id : ''
                    })
                )),
                amendmentDetails: klona(data.amendmentDetails),
                note: data.note,
                motivation: finalDialogData.motivation,
                rejectedReason: finalDialogData.reason,
                rejectedReasonSubject: finalDialogData.subject
            }

            const formDataToSend = new FormData();
            const jsonBlob = new Blob([JSON.stringify(submitData)], {
                type: 'application/json'
            });
            formDataToSend.append('applicationEvaluationFormRequestBean', jsonBlob);

            if (finalDialogData.files && finalDialogData.files.length > 0) {
                finalDialogData.files.forEach((file) => {
                    formDataToSend.append('rejectedDocuments', file);
                });
            }

            setLoading(true);
            setIsVisibleCompleteDialog(false);
            ApplicationEvaluationService.updateEvaluationV2(
                data.assignedApplicationId,
                formId,
                formDataToSend,
                approveRejectCallback,
                errApproveRejectCallback
            );
        }
    }, [data, finalDialogData]);

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

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

    const displayCriterionData = (id) => {
        const criterion = head(data.criteria.filter(o => o.id === id));
        setCriterionDataTitle(criterion.label);
        const content = <div className="criterionRelatedData">
            <h3>{__('I campi correlati')}</h3>
            {criterion.criteriaMappedFields ? criterion.criteriaMappedFields.map(o => criteriaDataItem(o)) : null}
        </div>;
        setCriterionDataContent(content);
        setIsVisibleCriterionData(id);
    }

    const criteriaDataItem = (item) => {
        let content = '';

        switch (item.fieldName) {
            case 'fileupload' :
                content = <ul>
                    {item.fieldValue
                        ? item.fieldValue.map(o => <li key={o.id}>
                            {o.filePath ? <a href={o.filePath}>{o.name}</a> : null}
                        </li>)
                        : null}
                </ul>;
                break;
            case 'table' :
                const th = Object.keys(item.fieldValue[0]);
                content = <table>
                    <thead>
                    <tr>
                        {th.map(v => <th key={v}>{v}</th>)}
                    </tr>
                    </thead>
                    <tbody>
                    {item.fieldValue
                        ? item.fieldValue.map((o, i) => <tr key={i}>
                            {Object.values(o).map(v => <td key={v}>{v}</td>)}
                        </tr>)
                        : null}
                    </tbody>
                </table>;
                break;
            default :
                content = item.fieldValue;
                break;
        }

        return <div key={item.id} className="criterionRelatedData__item">
            <strong>{item.fieldLabel}</strong>
            {content}
        </div>
    }

    const hideCriterionData = () => {
        setIsVisibleCriterionData(0);
        setCriterionDataTitle('');
        setCriterionDataContent('');
    }

    const getAmendmentsCallback = (data) => {
        if (data.status === 'SUCCESS') {
            if (data.data.length) {
                setConnectedSoccorsoId(data.data[0].id);
            } else {
                setConnectedSoccorsoId(0);
            }
        }
    }

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

    const shouldDisableField = useCallback((fieldName) => {
        return ['EXPIRED', 'CLOSE'].includes(data.status)
            || (['ADMISSIBLE', 'TECHNICAL_EVALUATION', 'TECHNICAL_EVALUATION', 'AWAITING_TECHNICAL_EVALUATION'].includes(data.applicationStatus)
                && !['criteria', 'note', 'files', 'amendmentDetails'].includes(fieldName))
    }, [data.applicationStatus]);

    const headerCompleteDialog = () => {
        return 'approve' === operationType
            ? <span>{__('Confermare l\'approvazione', 'gepafin')}</span>
            : <span>{__('Confermare il rifiuto', 'gepafin')}</span>;
    }

    const hideCompleteDialog = () => {
        setIsVisibleCompleteDialog(false);
        setOperationType('');
        setFinalDialogData({});
    }

    const footerCompleteDialog = useCallback(() => {
        let onSubmitAction;
        let isDisabled = loading;

        if (operationType === 'approve') {
            onSubmitAction = doApprove;
            isDisabled = isDisabled || !finalDialogData.amount || isEmpty(finalDialogData.amount) || finalDialogData.amount === 0;
        } else if (operationType === 'tf_reject') {
            onSubmitAction = () => doReject('TECHNICAL_EVALUATION_REJECTED');
        } else {
            onSubmitAction = () => doReject('REJECTED');
            isDisabled = isDisabled || !finalDialogData.reason || isEmpty(finalDialogData.reason)
        }

        return <div>
            <Button type="button" label={__('Annulla', 'gepafin')} onClick={hideCompleteDialog} outlined/>
            <Button
                type="button"
                disabled={isDisabled}
                label={__('Invia', 'gepafin')} onClick={onSubmitAction}/>
        </div>
    }, [finalDialogData, data]);

    const updateFinalDialogData = (value, path) => {
        const newData = wrap(finalDialogData).set(path.split('.'), value).value();
        setFinalDialogData(newData);
    };

    const initiateApproving = () => {
        setOperationType('approve');
        setFinalDialogData({
            amount: data.amountAccepted,
            motivation: ''
        });
        setIsVisibleCompleteDialog(true);

    }

    const initiateRejecting = () => {
        setOperationType('reject');
        setIsVisibleCompleteDialog(true);
    }

    /*const initiateTFRejecting = () => {
        setOperationType('tf_reject');
        setIsVisibleCompleteDialog(true);
    }*/

    const doCheckNDG = () => {
        doSaveDraft(doGetNDGRequest);
    }

    const doGetNDGRequest = () => {
        storeSet('setAsyncRequest');
        AppointmentService.getNdg(id, getNdgCallback, errGetNdgCallback);
    }

    const getNdgCallback = (data) => {
        if (data.status === 'SUCCESS') {
            if (toast.current && data.message) {
                toast.current.show({
                    severity: 'success',
                    summary: '',
                    detail: data.message
                });
            }
            if (data.data?.ndg) {
                setData((data) => ({
                    ...data,
                    ndg: data.data?.ndg
                }));
            }
        }
        storeSet('unsetAsyncRequest');
    }

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

    /*const doCreateAppointment = () => {
        setAppointmentData({
            title: '',
            text: '',
            duration: 0,
            amount: 0
        });
        setIsVisibleAppointmentDialog(true);
    }*/

    const setAppointmentFieldValue = (name, value) => {
        const newData = wrap(appointmentData).set(name, value).value();
        setAppointmentData(newData);
    }

    const headerAppointmentDialog = () => {
        return <span>{__('Crea appuntamento', 'gepafin')}</span>;
    }

    const hideAppointmentDialog = () => {
        setIsVisibleAppointmentDialog(false);
        setAppointmentData({});
    }

    const footerAppointmentDialog = () => {
        return <div>
            <Button type="button" label={__('Annulla', 'gepafin')} onClick={hideAppointmentDialog} outlined/>
            <Button
                type="button"
                disabled={loading}
                label={__('Invia', 'gepafin')} onClick={doCreateAppointmentRequest}/>
        </div>
    }

    const setPreTecEvalFieldValue = (name, value) => {
        const newData = wrap(preTecEvalData).set(name, value).value();
        setPreTecEvalData(newData);
    }

    const setBlueTongueFieldValue = (name, value) => {
        const numVal = value ?? 0;
        const updated = wrap(preTecEvalData).set(name, numVal).value();
        const field1 = name === 'blueTongueField1' ? numVal : (updated.blueTongueField1 ?? 0);
        const field2 = name === 'blueTongueField2' ? numVal : (updated.blueTongueField2 ?? 0);
        setPreTecEvalData(wrap(updated).set('amount', field1 + field2).value());
    };

    const headerPreTecEvalDialog = () => {
        return <span>{__('Valutazione Tecnico-Finanziaria', 'gepafin')}</span>;
    }

    const hidePreTecEvalDialog = () => {
        setIsVisiblePreTecEvalDialog(false);
        setPreTecEvalData({
            amendmentDocumentType: '',
            amount: 0,
            blueTongueField1: 0,
            blueTongueField2: 0
        });
    }

    const footerPreTecEvalDialog = useCallback(() => {
        const amount = pathOr(null, ['amount'], preTecEvalData);
        const isBlueTongue = preTecEvalData.amendmentDocumentType === 'BLUE_TONGUE';
        const field1 = pathOr(null, ['blueTongueField1'], preTecEvalData);
        const field2 = pathOr(null, ['blueTongueField2'], preTecEvalData);
        const isBlueTongueInvalid = isBlueTongue && (
            isNil(field1) || isNaN(parseFloat(field1)) ||
            isNil(field2) || isNaN(parseFloat(field2)) ||
            parseFloat(field1) + parseFloat(field2) <= 0
        );
        const isAmountInvalid = isNil(amount) || isNaN(parseFloat(amount)) || parseFloat(amount) <= 0;
        return <div>
            <Button type="button" label={__('Annulla', 'gepafin')} onClick={hidePreTecEvalDialog} outlined/>
            <Button
                type="button"
                disabled={loading || (isBlueTongue ? isBlueTongueInvalid : isAmountInvalid)}
                label={__('Invia', 'gepafin')} onClick={startCreatingSpecialAmendment}/>
        </div>
    }, [preTecEvalData]);

    const doCreateAppointmentRequest = () => {
        if (
            !isEmpty(appointmentData.title) && !isEmpty(appointmentData.text) && !isEmpty(appointmentData.amount)
            && !isEmpty(appointmentData.duration) && appointmentData.duration !== 0 && appointmentData.amount !== 0
        ) {
            storeSet('setAsyncRequest');
            const submitData = {
                'importoBreveTermine': appointmentData.amount,
                'durataMesiFinanziamento': appointmentData.duration,
                'nota': {
                    'titolo': appointmentData.title,
                    'testo': appointmentData.text
                }
            }

            AppointmentService.createAppointment(id, submitData, getAppointmentCallback, errGetAppointemntCallback);
        }
    }

    const getAppointmentCallback = (data) => {
        if (data.status === 'SUCCESS') {
            if (toast.current && data.message) {
                toast.current.show({
                    severity: 'success',
                    summary: '',
                    detail: data.message
                });
            }
            if (data.data.appointmentId) {
                setData({
                    ...data,
                    appointmentId: data.data.appointmentId
                });
            }
        }
        setIsVisibleAppointmentDialog(false);
        storeSet('unsetAsyncRequest');
    }

    const errGetAppointemntCallback = (data) => {
        if (toast.current && data.message) {
            toast.current.show({
                severity: data.status === 'SUCCESS' ? 'info' : 'error',
                summary: '',
                detail: data.message
            });
        }
        setIsVisibleAppointmentDialog(false);
        set404FromErrorResponse(data);
        storeSet('unsetAsyncRequest');
    }

    const startCreatingSpecialAmendment = () => {
        doSaveDraft(doCreateSpecialAmendment);
    }

    const doCreateSpecialAmendment = useCallback(() => {
        if (
            !isEmpty(preTecEvalData.amount) && !isNil(preTecEvalData.amount)
            && !isNaN(parseInt(preTecEvalData.amount)) && parseFloat(preTecEvalData.amount) >= 0 && !isEmpty(preTecEvalData.amendmentDocumentType)
        ) {
            storeSet('setAsyncRequest');

            AmendmentsService.createAmendmentSpecial(preTecEvalData, getAmendmentSpecialCallback, errGetAmendmentSpecialCallback,
                [
                    ['applicationEvaluationId', data.id]
                ]);
        }
    }, [preTecEvalData, data]);

    const getAmendmentSpecialCallback = (data) => {
        if (data.status === 'SUCCESS') {
            setConnectedSoccorsoId(data.data.id);
            setData(prev => ({
                ...prev,
                applicationStatus: 'AWAITING_TECHNICAL_EVALUATION',
                status: 'SOCCORSO'
            }));
            if (toast.current && data.message) {
                toast.current.show({
                    severity: 'success',
                    summary: '',
                    detail: data.message
                });
            }
        }
        setIsVisiblePreTecEvalDialog(false);
        setPreTecEvalData({
            amendmentDocumentType: '',
            amount: 0,
            blueTongueField1: 0,
            blueTongueField2: 0
        });
        storeSet('unsetAsyncRequest');
    }

    const errGetAmendmentSpecialCallback = (data) => {
        if (toast.current && data.message) {
            toast.current.show({
                severity: data.status === 'SUCCESS' ? 'info' : 'error',
                summary: '',
                detail: data.message
            });
        }
        setIsVisiblePreTecEvalDialog(false);
        setPreTecEvalData({
            amendmentDocumentType: '',
            amount: 0,
            blueTongueField1: 0,
            blueTongueField2: 0
        });
        set404FromErrorResponse(data);
        storeSet('unsetAsyncRequest');
    }

    const doMakeAdmisible = () => {
        doSaveDraft(null, {
            applicationStatus: 'ADMISSIBLE'
        });
    }

    const doPassTechnicalEvaluation = useCallback(() => {
        if (isAdmissible) {
            doSaveDraft(null, {
                applicationStatus: 'TECHNICAL_EVALUATION'
            });
        }
    }, [isAdmissible]);

    const evaluationBlockedForUser = (data = {}) => {
        const userData = storeGet('userData');
        return isAsyncRequest || userData.id !== data.assignedUserId;
    }

    const shouldDisableNewSoccorso = () => {
        if (APP_HUB_ID !== 't7jh5wfg9QXylNaTZkPoE') {
            //return !data.ndg || !data.appointmentId || !allFilesRated || !atLeastOneChecked;
            return !data?.ndg || !allFilesRated || !atLeastOneChecked;
        } else if (APP_HUB_ID === 't7jh5wfg9QXylNaTZkPoE') {
            return !allFilesRated || !atLeastOneChecked;
        } else {
            return true;
        }
    }

    const updateStatusOfAppl = useCallback((newStatus) => {
        const newData = wrap(data).set(['applicationStatus'], newStatus).value();
        setData(newData);
    }, [data]);

    /*const openSendContractForm = () => {
        setIsVisibleContractForm(true);
    }
    const headerContractDialog = () => {
        return <span>{__('Invia il contratto', 'gepafin')}</span>;
    }
    const hideContractDialog = () => {
        setIsVisibleContractForm(false);
        setContractFormData({
            subject: '',
            text: ''
        });
    }
    const footerContractDialog = useCallback(() => {
        let isDisabled = !contractFormData.subject || isEmpty(contractFormData.subject)
            || !contractFormData.text || isEmpty(contractFormData.text)
            || !contractFormData.files || isEmpty(contractFormData.files) || isAsyncRequest;

        return <div>
            <Button type="button" label={__('Annulla', 'gepafin')} onClick={hideContractDialog} outlined/>
            <Button
                type="button"
                disabled={isDisabled}
                label={__('Invia', 'gepafin')} onClick={doSendContract}/>
        </div>
    }, [contractFormData]);
    const updateContractFormData = (value, path) => {
        const newData = wrap(contractFormData).set(path.split('.'), value).value();
        setContractFormData(newData);
    };
    const doSendContract = useCallback(() => {
        if (
            contractFormData.subject && !isEmpty(contractFormData.subject)
            && contractFormData.text && !isEmpty(contractFormData.text)
            && contractFormData.files && !isEmpty(contractFormData.files)
        ) {
            const formDataToSend = new FormData();
            const contractFormDataTemp = {
                ...contractFormData
            };
            delete contractFormDataTemp.files;
            const jsonBlob = new Blob([JSON.stringify(contractFormDataTemp)], {
                type: 'application/json'
            });
            formDataToSend.append('applicationContractRequest', jsonBlob);

            if (contractFormData.files && contractFormData.files.length > 0) {
                contractFormData.files.forEach((file) => {
                    formDataToSend.append('contractDocuments', file);
                });
            }

            storeSet('setAsyncRequest');

            ApplicationContractService.uploadApplicationContract(
                data.applicationId,
                formDataToSend,
                getUploadApplicationContractCallback,
                errGetUploadApplicationContractCallback
            );
        }
    }, [contractFormData]);
    const getUploadApplicationContractCallback = (data) => {
        if (data.status === 'SUCCESS') {
            setData((prev) => ({
                ...prev,
                applicationStatus: 'AWAITING_CONTRACT',
                contract: data.data
            }));
            if (toast.current && data.message) {
                toast.current.show({
                    severity: 'success',
                    summary: '',
                    detail: data.message
                });
            }
        }
        hideContractDialog();
        storeSet('unsetAsyncRequest');
    }
    const errGetUploadApplicationContractCallback = (data) => {
        if (toast.current && data.message) {
            toast.current.show({
                severity: data.status === 'SUCCESS' ? 'info' : 'error',
                summary: '',
                detail: data.message
            });
        }
        hideContractDialog();
        set404FromErrorResponse(data);
        storeSet('unsetAsyncRequest');
    }*/

    const actionBtns = () => {
        return <div className="appPageSection__actions">
            {(['SOCCORSO', 'CLOSE', 'EVALUATION', 'NDG', 'APPOINTMENT', 'ADMISSIBLE',
                    'AWAITING_TECHNICAL_EVALUATION', 'TECHNICAL_EVALUATION'].includes(data.applicationStatus)
                && APP_HUB_ID !== 't7jh5wfg9QXylNaTZkPoE')
            || (['SOCCORSO', 'CLOSE', 'EVALUATION', 'ADMISSIBLE', 'TECHNICAL_EVALUATION'].includes(data.applicationStatus)
                && APP_HUB_ID === 't7jh5wfg9QXylNaTZkPoE')
                ? <Button
                    type="button"
                    disabled={!data.id || ['EXPIRED', 'CLOSE'].includes(data.status)
                        || (!['SOCCORSO', 'AWAITING_TECHNICAL_EVALUATION'].includes(data.applicationStatus) && shouldDisableNewSoccorso())
                        || evaluationBlockedForUser(data)}
                    onClick={doNewSoccorso}
                    outlined
                    label={<>
                        {connectedSoccorsoId === 0
                            ? __('Richiedi soccorso istruttorio', 'gepafin')
                            : __('Apri soccorso istruttorio', 'gepafin')}
                        <i style={{ marginLeft: 7 }}>
                            <HelpIcon/>
                        </i>
                    </>}
                /> : null}
            {data.id
                ? <Button
                    type="button"
                    disabled={['EXPIRED', 'CLOSE'].includes(data.status) || evaluationBlockedForUser(data)}
                    onClick={() => doSaveDraft()}
                    outlined
                    label={__('Salva bozza valutazione', 'gepafin')}
                    icon="pi pi-save" iconPos="right"/>
                : <Button
                    type="button"
                    onClick={() => doSaveDraft()}
                    label={__('Crea valutazione', 'gepafin')}
                    icon="pi pi-save" iconPos="right"/>}
            {APP_EVALUATION_FLOW_ID === '1' && APP_HUB_ID !== 't7jh5wfg9QXylNaTZkPoE'
                ? <Button
                    type="button"
                    disabled={!data.id
                        || !['EVALUATION'].includes(data.applicationStatus) || evaluationBlockedForUser(data)}
                    onClick={doCheckNDG}
                    label={__('Controlla NDG', 'gepafin')}
                /> : null}
            {/*{APP_EVALUATION_FLOW_ID === '1' && APP_HUB_ID !== 't7jh5wfg9QXylNaTZkPoE'
                ? <Button
                    type="button"
                    disabled={!data.id || !['NDG'].includes(data.applicationStatus) || !data.ndg || evaluationBlockedForUser(data)}
                    onClick={doCreateAppointment}
                    label={__('Crea l\'appuntamento', 'gepafin')}
                /> : null}*/}
            {APP_HUB_ID !== 't7jh5wfg9QXylNaTZkPoE'
                ? <Button
                    type="button"
                    disabled={!data.id || !allFilesRated || !allChecksChecked
                        || !['NDG'].includes(data.applicationStatus) || evaluationBlockedForUser(data) || connectedSoccorsoId !== 0}
                    onClick={doMakeAdmisible}
                    label={__('Ammissibile formalmente', 'gepafin')}
                />
                : <Button
                    type="button"
                    disabled={!data.id || !allFilesRated || !allChecksChecked
                        || evaluationBlockedForUser(data) || connectedSoccorsoId !== 0}
                    onClick={doMakeAdmisible}
                    label={__('Ammissibile formalmente', 'gepafin')}
                />}
            {/* Removed for Sviluppumbria */}
            {/*{APP_HUB_ID === 't7jh5wfg9QXylNaTZkPoE'
                ? <Button
                    type="button"
                    disabled={!data.id || !['ADMISSIBLE'].includes(data.applicationStatus) || evaluationBlockedForUser(data) || connectedSoccorsoId !== 0}
                    onClick={doPassTechnicalEvaluation}
                    icon="pi pi-info-circle" iconPos="right"
                    tooltip={isAdmissible
                        ? __('Punteggio sufficiente per passaggio alla valutazione tecnica ed economico finanziaria', 'gepafin')
                        : __('Punteggio non sufficiente per passaggio alla valutazione tecnica ed economico finanziaria', 'gepafin')}
                    severity={isAdmissible ? 'success' : 'warning'}
                    label={__('Valutazione tecnico-finanziaria positiva', 'gepafin')}
                /> : null}*/}
            {APP_HUB_ID !== 't7jh5wfg9QXylNaTZkPoE' && data.applicationStatus === 'AWAITING_TECHNICAL_EVALUATION'
                ? <Button
                    type="button"
                    disabled={!data.id || !['ADMISSIBLE'].includes(data.applicationStatus) || evaluationBlockedForUser(data) || connectedSoccorsoId !== 0}
                    onClick={doPassTechnicalEvaluation}
                    icon="pi pi-info-circle" iconPos="right"
                    tooltip={isAdmissible
                        ? __('Punteggio sufficiente per passaggio alla valutazione tecnica ed economico finanziaria', 'gepafin')
                        : __('Punteggio non sufficiente per passaggio alla valutazione tecnica ed economico finanziaria', 'gepafin')}
                    severity={isAdmissible ? 'success' : 'warning'}
                    label={__('Valutazione tecnico-finanziaria positiva', 'gepafin')}
                />
                : APP_HUB_ID !== 't7jh5wfg9QXylNaTZkPoE'
                    ? <SplitButton
                        ref={tecFinBtnRef}
                        disabled={!data.id || !['ADMISSIBLE'].includes(data.applicationStatus)
                            || evaluationBlockedForUser(data) || connectedSoccorsoId !== 0 || !isAdmissible}
                        label={__('Valutazione tecnico-finanziaria', 'gepafin')}
                        onClick={(e) => {
                            tecFinBtnRef.current.show(e);
                        }}
                        tooltip={isAdmissible
                            ? __('Punteggio sufficiente per passaggio alla valutazione tecnica ed economico finanziaria', 'gepafin')
                            : __('Punteggio non sufficiente per passaggio alla valutazione tecnica ed economico finanziaria', 'gepafin')}
                        severity={isAdmissible ? 'success' : 'warning'}
                        model={tecnicalEvalItems}/> : null}
            {/*<Button
                type="button"
                disabled={!data.id || !['TECHNICAL_EVALUATION'].includes(data.applicationStatus) || evaluationBlockedForUser(data)}
                onClick={initiateTFRejecting}
                icon="pi pi-info-circle" iconPos="right"
                severity={isAdmissible ? 'success' : 'warning'}
                label={__('Respingi domanda per valutazione TF negativa', 'gepafin')}
            />*/}
            {data.id
                ? <Button
                    type="button"
                    disabled={!isAdmissible
                        || ['APPROVED', 'REJECTED'].includes(data.applicationStatus)
                        || evaluationBlockedForUser(data)
                        || (APP_EVALUATION_FLOW_ID === '1' && !['AWAITING_TECHNICAL_EVALUATION'].includes(data.applicationStatus))
                        || connectedSoccorsoId !== 0
                    }
                    onClick={initiateApproving}
                    label={__('Domanda in Graduatoria Definitiva', 'gepafin')}
                    icon="pi pi-check" iconPos="right"/> : null}
            {data.id
                ? <Button
                    type="button"
                    disabled={['APPROVED', 'REJECTED'].includes(data.applicationStatus)
                        || evaluationBlockedForUser(data)}
                    onClick={initiateRejecting}
                    label={__('Respingi domanda', 'gepafin')}
                    icon="pi pi-times" iconPos="right"/> : null}
            {/*
            This functionality has been moved
            */}
            {/*{APP_HUB_ID !== 't7jh5wfg9QXylNaTZkPoE' && data.applicationStatus === 'APPROVED'
                ? <Button
                    type="button"
                    disabled={!data.id}
                    onClick={openSendContractForm}
                    label={__('Invia il contratto', 'gepafin')}
                /> : null}*/}
        </div>
    }

    const auxActions = () => {
        return <div className="appPageSection__actions">
            <SoccorsoResendEmails
                emailsData={emailSendResponse}
                setDataEmailsSoccorso={updateEmailSendResponses}/>
            <EvaluationReAdmit id={data.applicationId} status={data.applicationStatus}
                               statusUpdateFn={updateStatusOfAppl}/>
        </div>
    }

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

    const rejectionFiles = () => {
        return data.rejectedDocument && !isEmpty(data.rejectedDocument) && ['REJECTED'].includes(data.applicationStatus)
            ? <ul>
                {data.rejectedDocument.map(o => <li key={o.id}>
                    <a href={o.filePath}>{o.name}</a>
                </li>)}
            </ul> : null
    }

    const motivationMsg = () => {
        return data.motivation && !isEmpty(data.motivation) && ['REJECTED', 'APPROVED'].includes(data.applicationStatus)
            ? <div className="appPageSection__message info">
                <i className="pi pi-info-circle"></i>
                <span className="summary">{__('Motivazione:', 'gepafin')}</span>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    <span>{renderHtmlContent(data.motivation)}</span>
                    {rejectionFiles()}
                </div>
            </div> : null
    }

    useEffect(() => {
        let updatedFormValues = klona(formValues);
        let context = {};

        // eslint-disable-next-line array-callback-return
        formData.map((o) => {
            const variable = head(o.settings.filter(o => o.name === 'variable'));
            const formula = head(o.settings.filter(o => o.name === 'formula'));

            if (formula && !isEmpty(formula.value)) {
                try {
                    context = getTokens(formula.value)
                        .filter(v => !['false', 'null', 'true'].includes(v))
                        .reduce((acc, cur) => {
                            acc[cur] = isNil(context[cur]) ? 0 : parseCommaDecimal(context[cur]);
                            return acc;
                        }, context);
                } catch {
                    console.error('Error in formula', formula)
                    context = {}
                }

                const mathFormula = renderWithDataVars(formula.value, context);
                try {
                    updatedFormValues[o.id] = evaluate(mathFormula);
                } catch (e) {
                    console.log('Error in math formula: "', mathFormula, '"', e.message);
                    updatedFormValues[o.id] = 0;
                }
            }

            if (variable && !isEmpty(variable.value)) {
                context[variable.value[0]] = 'criteria_table' === o.name
                    ? pathOr(0, [o.id, 'total'], updatedFormValues)
                    : pathOr(0, [o.id], updatedFormValues);
            }
        });

        if (!isEmpty(updatedFormValues) && !equal(updatedFormValues, formValues)) {
            reset(updatedFormValues);
        }

        updateFlagsForSoccorso(data);
    }, [formValues]);

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

    useEffect(() => {
        const maxScore = pathOr(0, ['minScore'], data);
        const criteria = pathOr([], ['criteria'], data);
        const scoreSum = pathOr(0, [], sum(criteria.map(o => o.score)));

        setIsAdmissible(scoreSum >= maxScore);
    }, [data]);

    const refetchEvaluation = useCallback(() => {
        const parsed = parseInt(id);
        const entityId = !isNaN(parsed) ? parsed : 0;
        storeSet('setAsyncRequest');
        ApplicationEvaluationService.getEvaluationVersionByApplId(entityId, getVersion, errGetVersion);
    }, [id]);

    useEffect(() => {
        refetchEvaluation();
        const parsed = parseInt(id)
        const entityId = !isNaN(parsed) ? parsed : 0;
        AmendmentsService.getSoccorsoByApplId(entityId, getAmendmentsCallback, errGetAmendmentsCallback, [
            ['statuses', ['AWAITING', 'RESPONSE_RECEIVED']]
        ]);
    }, [id]);

    return (
        <div className="appPage">
            <div className="appPage__pageHeader">
                <h1>{__('Valuta domanda', 'gepafin')}</h1>
            </div>

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

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

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

            {!isAsyncRequest && !isEmpty(data)
                ? <div className="appPage__content">
                    <ApplicationInfo data={data}/>

                    <div className="appPageSection">
                        {motivationMsg()}
                    </div>

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

                    <div className="appPageSection">
                        {actionBtns()}
                        {auxActions()}
                    </div>

                    <div className="appPageSection__hr"></div>

                    <ApplicationDownloadFiles id={id}/>

                    <div className="appPageSection">
                        <h2>{__('Documenti aggiuntivi', 'gepafin')}</h2>
                        <EvaluationExtraFiles
                            defaultValue={data.evaluationDocument ?? []}
                            updateFn={(data) => updateEvaluationValue(
                                data,
                                ['evaluationDocument']
                            )}
                            updateCallbackFn={(files) => doSaveDraft(
                                null,
                                {
                                    evaluationDocument: klona(files.map(o => ({
                                            ...o,
                                            fileValue: o.fileValue[0] ? o.fileValue[0].id : ''
                                        })
                                    ))
                                })}
                            refetchFn={refetchEvaluation}
                            shouldDisable={['APPROVED', 'REJECTED'].includes(data.applicationStatus) || evaluationBlockedForUser(data)}
                            sourceId={data.id}
                            applicationId={data.applicationId}
                            companyId={data.companyId}
                            sourceName="evaluation"/>
                    </div>

                    <div className="appPageSection">
                        <h2>{__('Note', 'gepafin')}</h2>
                        <div translate="no" style={{ 'width': '100%' }}>
                            <Editor
                                value={data.note}
                                readOnly={shouldDisableField('note') || evaluationBlockedForUser(data)}
                                placeholder={__('Digita qui il messagio', 'gepafin')}
                                headerTemplate={header}
                                onTextChange={(e) => updateEvaluationValue(
                                    e.htmlValue,
                                    ['note']
                                )}
                                style={{ height: 80 * 3, width: '100%' }}
                            />
                        </div>
                    </div>

                    {data.evaluationVersion === 'V2'
                        ? <div className="appPageSection">
                            {APP_HUB_ID !== 't7jh5wfg9QXylNaTZkPoE'
                                ? <>
                                    <h3>{__('Contratto', 'gepafin')}</h3>
                                    {data.contract && data.contract?.beneficiaryDocuments && !isEmpty(data.contract?.beneficiaryDocuments)
                                        ? <ol className="appPageSection__list">
                                            {data.contract?.beneficiaryDocuments.map(o => <li key={o.id}
                                                                                              className="appPageSection__listItem">
                                                <div className="appPageSection__listItemRow">
                                                    <div>{renderHtmlContent(o.name)}</div>
                                                    <div className="appPageSection__iconActions">
                                                        <Button icon="pi pi-eye" rounded
                                                                onClick={() => {
                                                                    window.open(o.fileDetail[0].filePath, '_blank').focus()
                                                                }}
                                                                outlined severity="info"
                                                                aria-label={__('Mostra', 'gepafin')}/>
                                                        <ArchiveDocument
                                                            ndg={data?.ndg}
                                                            applicationId={id}
                                                            fileDescr={renderHtmlContent(o.name)}
                                                            fileId={o.id}
                                                            updateFn={(attachId) => {
                                                                setData((prev) => {
                                                                    const newDocuments = data.contract.beneficiaryDocuments
                                                                        .map(ob => {
                                                                            return ob.id === o.id
                                                                                ? {
                                                                                    ...o,
                                                                                    documentAttachmentId: attachId
                                                                                }
                                                                                : o;
                                                                        });
                                                                    return {
                                                                        ...prev,
                                                                        contract: {
                                                                            ...prev.contract,
                                                                            beneficiaryDocuments: newDocuments
                                                                        }
                                                                    }
                                                                });
                                                            }}
                                                            isSignedDocument={true}
                                                            docAttachmentId={o.documentAttachmentId}/>
                                                    </div>
                                                </div>
                                            </li>)}
                                        </ol>
                                        : <p>{__('Nessun documento firmato', 'gepafin')}</p>}
                                </> : null}
                            <h2>{__('Domanda PDF firmato', 'gepafin')}</h2>
                            {data.signedDocument && !isEmpty(data.signedDocument)
                                ? <ol className="appPageSection__list">
                                    <li className="appPageSection__listItem">
                                        <div className="appPageSection__listItemRow">
                                            <div>{renderHtmlContent(data.signedDocument.fileName)}</div>
                                            <div className="appPageSection__iconActions">
                                                <ArchiveDocument
                                                    ndg={data?.ndg}
                                                    applicationId={id}
                                                    fileDescr={renderHtmlContent(data.signedDocument.fileName)}
                                                    fileId={data.signedDocument.id}
                                                    updateFn={(attachId) => {
                                                        setData((prev) => ({
                                                            ...prev,
                                                            signedDocument: {
                                                                ...prev.signedDocument,
                                                                documentAttachmentId: attachId
                                                            }
                                                        }));
                                                    }}
                                                    isSignedDocument={true}
                                                    docAttachmentId={data.signedDocument.documentAttachmentId}/>
                                            </div>
                                        </div>
                                    </li>
                                </ol>
                                : <p>{__('Nessun documento firmato', 'gepafin')}</p>}
                            <h2>{__('Documenti allegati', 'gepafin')}</h2>
                            {!isEmpty(data.files)
                                ? <ListOfFiles
                                    files={data.files}
                                    updateFn={updateEvaluationValue}
                                    shouldDisableFieldFn={(name) => shouldDisableField(name) || evaluationBlockedForUser(data)}
                                    name="files"
                                    ndg={data?.ndg}
                                    applicationId={id}/>
                                : <p>{__('Nessun documento allegato', 'gepafin')}</p>}
                        </div>
                        : null}

                    {data.evaluationVersion === 'V2'
                        ? <form className="appForm" onSubmit={handleSubmit(() => {
                        })}>
                            {formData.map(o => {
                                const label = head(o.settings.filter(o => o.name === 'label'));
                                const text = head(o.settings.filter(o => o.name === 'text'));
                                const placeholder = head(o.settings.filter(o => o.name === 'placeholder'));
                                const options = head(o.settings.filter(o => o.name === 'options'));
                                let tableColumns = head(o.settings.filter(o => o.name === 'table_columns'));
                                if (!tableColumns) {
                                    tableColumns = head(o.settings.filter(o => o.name === 'criteria_table_columns'));
                                }
                                const template = head(o.settings.filter(s => s.name === 'template'));
                                const step = head(o.settings.filter(o => o.name === 'step'));
                                const mime = head(o.settings.filter(o => o.name === 'mime'));
                                const formula = head(o.settings.filter(o => o.name === 'formula'));
                                let mimeValue = '';

                                if (mime) {
                                    mimeValue = mime.value.map(o => o.code ? o.code : o.ext);
                                }

                                const validations = Object.keys(o.validators).reduce((acc, cur) => {
                                    if (o.validators[cur]) {
                                        if (['min', 'max', 'minLength', 'maxLength', 'maxSize'].includes(cur)) {
                                            acc[cur] = parseInt(o.validators[cur]);
                                        } else if ('pattern' === cur) {
                                            acc[cur] = new RegExp(o.validators[cur]);
                                        } else if ('isRequired' === cur) {
                                            //acc[cur] = o.validators[cur];
                                            acc['required'] = true;
                                        } else if ('custom' === cur && validationFns[o.validators[cur]]) {
                                            if (!acc.validate) {
                                                acc.validate = {};
                                            }
                                            acc.validate[o.validators[cur]] = validationFns[o.validators[cur]];
                                        }
                                    }

                                    return acc;
                                }, {});

                                /*if (o.name === 'table') {
                                    console.log('value:', values[o.id] ? values[o.id] : '')
                                }*/

                                return ['paragraph'].includes(o.name) && text
                                    ? <div key={o.id}>
                                        <div className="ql-editor">
                                            {renderHtmlContent(text.value)}
                                        </div>
                                    </div>
                                    : <FormField
                                        key={o.id}
                                        readOnly={formula && !isEmpty(formula.value)}
                                        type={o.name}
                                        fieldName={o.id}
                                        label={label ? label.value : ''}
                                        placeholder={placeholder ? placeholder.value : ''}
                                        control={control}
                                        register={register}
                                        errors={errors}
                                        defaultValue={values[o.id] ? values[o.id] : ''}
                                        maxFractionDigits={step ? step.value : 0}
                                        accept={mimeValue}
                                        config={validations}
                                        options={options ? options.value : []}
                                        setDataFn={setValue}
                                        saveFormCallback={doSaveDraft}
                                        sourceId={id}
                                        useGrouping={false}
                                        tableColumns={tableColumns ? tableColumns.value : {}}
                                        template={template ? template.value : null}
                                    />
                            })}
                        </form>
                        : null}

                    {data.evaluationVersion === 'V1'
                        ? <div className="appPageSection">
                            <h2>{__('Checklist Valutazione', 'gepafin')}</h2>
                            <div className="appPageSection columns">
                                <div>
                                    <h3>{__('Lista', 'gepafin')}</h3>
                                    <div className="appPageSection__withBorder grey" style={{ marginBottom: '20px' }}>
                                        <div className="appPageSection__checklist">
                                            {data.checklist.map((o, i) => <div key={o.id}>
                                                <Checkbox
                                                    disabled={shouldDisableField('checklist') || evaluationBlockedForUser(data)}
                                                    inputId={`checklist_${o.id}`}
                                                    onChange={(e) => updateEvaluationValue(
                                                        e.checked,
                                                        ['checklist', i, 'valid']
                                                    )}
                                                    checked={o.valid}></Checkbox>
                                                <label htmlFor={`checklist_${o.id}`}>{o.label}</label>
                                            </div>)}
                                        </div>
                                    </div>
                                </div>
                                <div>
                                    {APP_HUB_ID !== 't7jh5wfg9QXylNaTZkPoE'
                                        ? <>
                                            <h3>{__('Contratto', 'gepafin')}</h3>
                                            {data.contract && data.contract?.beneficiaryDocuments && !isEmpty(data.contract?.beneficiaryDocuments)
                                                ? <ol className="appPageSection__list">
                                                    {data.contract?.beneficiaryDocuments.map(o => <li key={o.id}
                                                                                                      className="appPageSection__listItem">
                                                        <div className="appPageSection__listItemRow">
                                                            <div>{renderHtmlContent(o.name)}</div>
                                                            <div className="appPageSection__iconActions">
                                                                <Button icon="pi pi-eye" rounded
                                                                        onClick={() => {
                                                                            window.open(o.fileDetail[0].filePath, '_blank').focus()
                                                                        }}
                                                                        outlined severity="info"
                                                                        aria-label={__('Mostra', 'gepafin')}/>
                                                                <ArchiveDocument
                                                                    ndg={data?.ndg}
                                                                    applicationId={id}
                                                                    fileDescr={renderHtmlContent(o.name)}
                                                                    fileId={o.id}
                                                                    updateFn={(attachId) => {
                                                                        setData((prev) => {
                                                                            const newDocuments = data.contract.beneficiaryDocuments
                                                                                .map(ob => {
                                                                                    return ob.id === o.id
                                                                                        ? {
                                                                                            ...o,
                                                                                            documentAttachmentId: attachId
                                                                                        }
                                                                                        : o;
                                                                                });
                                                                            return {
                                                                                ...prev,
                                                                                contract: {
                                                                                    ...prev.contract,
                                                                                    beneficiaryDocuments: newDocuments
                                                                                }
                                                                            }
                                                                        });
                                                                    }}
                                                                    isSignedDocument={true}
                                                                    docAttachmentId={o.documentAttachmentId}/>
                                                            </div>
                                                        </div>
                                                    </li>)}
                                                </ol>
                                                : <p>{__('Nessun documento firmato', 'gepafin')}</p>}
                                        </> : null}
                                    <h3>{__('Domanda PDF firmato', 'gepafin')}</h3>
                                    {data.signedDocument && !isEmpty(data.signedDocument)
                                        ? <ol className="appPageSection__list">
                                            <li className="appPageSection__listItem">
                                                <div className="appPageSection__listItemRow">
                                                    <div>{renderHtmlContent(data.signedDocument.fileName)}</div>
                                                    <div className="appPageSection__iconActions">
                                                        <Button icon="pi pi-eye" rounded
                                                                onClick={() => {
                                                                    window.open(data.signedDocument.filePath, '_blank').focus()
                                                                }}
                                                                outlined severity="info"
                                                                aria-label={__('Mostra', 'gepafin')}/>
                                                        <ArchiveDocument
                                                            ndg={data?.ndg}
                                                            applicationId={id}
                                                            fileDescr={renderHtmlContent(data.signedDocument.fileName)}
                                                            fileId={data.signedDocument.id}
                                                            updateFn={(attachId) => {
                                                                setData((prev) => ({
                                                                    ...prev,
                                                                    signedDocument: {
                                                                        ...prev.signedDocument,
                                                                        documentAttachmentId: attachId
                                                                    }
                                                                }));
                                                            }}
                                                            isSignedDocument={true}
                                                            docAttachmentId={data.signedDocument.documentAttachmentId}/>
                                                    </div>
                                                </div>
                                            </li>
                                        </ol>
                                        : <p>{__('Nessun documento firmato', 'gepafin')}</p>}
                                    <h3>{__('Documenti allegati', 'gepafin')}</h3>
                                    {!isEmpty(data.files)
                                        ? <ListOfFiles
                                            files={data.files}
                                            updateFn={updateEvaluationValue}
                                            shouldDisableFieldFn={(name) => shouldDisableField(name) || evaluationBlockedForUser(data)}
                                            name="files"
                                            ndg={data?.ndg}
                                            applicationId={id}/>
                                        : <p>{__('Nessun documento allegato', 'gepafin')}</p>}
                                </div>
                            </div>
                        </div>
                        : null}

                    {!isEmpty(data.amendmentDetails)
                        ? <div className="appPageSection">
                            <h2>{__('Documenti di soccorso', 'gepafin')}</h2>
                            <ListOfFiles
                                files={data.amendmentDetails}
                                updateFn={updateEvaluationValue}
                                shouldDisableFieldFn={(name) => shouldDisableField(name) || evaluationBlockedForUser(data)}
                                name="amendmentDetails"
                                ndg={data?.ndg}
                                applicationId={id}/>
                        </div> : null}

                    {data.evaluationVersion === 'V1'
                        ? <div className="appPageSection">
                            <h2>{__('Punteggi di valutazione', 'gepafin')}</h2>
                            {data.criteria
                                ? <table className="myTable">
                                    <thead className="myThead">
                                    <tr>
                                        <th>{__('Parametro', 'gepafin')}</th>
                                        <th style={{ width: 200 }}>{__('Punteggio', 'gepafin')}</th>
                                        <th style={{ width: 220 }}>{__('Stato', 'gepafin')}</th>
                                    </tr>
                                    </thead>
                                    <tbody className="myTbody">
                                    {data.criteria.map((o, i) => <tr key={o.id}>
                                        <td>{o.label}</td>
                                        <td>
                                            <div className="p-inputgroup">
                                                <InputNumber
                                                    disabled={shouldDisableField('criteria') || evaluationBlockedForUser(data)}
                                                    placeholder={__('Punteggio', 'gepafin')}
                                                    value={o.score}
                                                    minFractionDigits={0}
                                                    maxFractionDigits={2}
                                                    max={o.maxScore}
                                                    onChange={(e) => updateEvaluationValue(
                                                        e.value,
                                                        ['criteria', i, 'score'],
                                                        o.maxScore
                                                    )}/>
                                                <span className="p-inputgroup-addon">
                                                / {o.maxScore}
                                            </span>
                                            </div>
                                        </td>
                                        <td>
                                            <div className="appPageSection__iconActions">
                                                {!isEmpty(o.criteriaMappedFields)
                                                    ? <Button icon="pi pi-eye"
                                                              rounded outlined severity="info"
                                                              onClick={() => displayCriterionData(o.id)}
                                                              aria-label={__('Mostra', 'gepafin')}/> : null}
                                                <Button icon="pi pi-thumbs-up" rounded outlined
                                                        disabled={shouldDisableField('criteria') || evaluationBlockedForUser(data)}
                                                        severity={!isNil(o.valid) && o.valid ? 'success' : 'secondary'}
                                                        onClick={() => updateEvaluationValue(
                                                            true,
                                                            ['criteria', i, 'valid']
                                                        )}
                                                        aria-label={__('Su', 'gepafin')}/>
                                                <Button icon="pi pi-thumbs-down" rounded outlined
                                                        disabled={shouldDisableField('criteria') || evaluationBlockedForUser(data)}
                                                        severity={!isNil(o.valid) && !o.valid ? 'danger' : 'secondary'}
                                                        onClick={() => updateEvaluationValue(
                                                            false,
                                                            ['criteria', i, 'valid']
                                                        )}
                                                        aria-label={__('Giu', 'gepafin')}/>
                                            </div>
                                        </td>
                                    </tr>)}
                                    <tr>
                                        <td>{__('Punteggio:', 'gepafin')}</td>
                                        <td>{new Intl.NumberFormat('it-IT').format(
                                            sum(data.criteria.map(o => o.score))
                                        )}</td>
                                        <td>
                                            {isAdmissible
                                                ? <Tag icon="pi pi-check" severity="success"
                                                       value={__('Punteggio sufficiente per passaggio alla valutazione tecnica ed economico finanziaria', 'gepafin')}></Tag> : null}
                                            {!isAdmissible
                                                ? <Tag icon="pi pi-times" severity="warning"
                                                       value={__('Punteggio non sufficiente per passaggio alla valutazione tecnica ed economico finanziaria', 'gepafin')}></Tag> : null}
                                        </td>
                                    </tr>
                                    </tbody>
                                    <tfoot className="myTfoot">
                                    <tr>
                                        <td colSpan="3">{sprintf(__('Punteggio minimo per l\'ammissione: %d'), data.minScore)}</td>
                                    </tr>
                                    </tfoot>
                                </table> : null}
                        </div>
                        : null}

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

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

                    <div className="appPageSection">
                        {actionBtns()}
                        {auxActions()}
                    </div>

                    <Dialog
                        header={criterionDataTitle}
                        visible={isVisibleCriterionData !== 0}
                        style={{ width: '50vw' }}
                        onHide={hideCriterionData}>
                        {criterionDataContent}
                    </Dialog>

                    <Dialog
                        visible={isVisibleCompleteDialog}
                        modal
                        header={headerCompleteDialog}
                        footer={footerCompleteDialog}
                        style={{ maxWidth: '600px', width: '100%' }}
                        onHide={hideCompleteDialog}>
                        {operationType === 'approve'
                            ? <div className="appForm__field">
                                <label
                                    className={classNames({ 'p-error': !finalDialogData.amount || isEmpty(finalDialogData.amount) || finalDialogData.amount === 0 })}>
                                    {__('Importo approvato', 'gepafin')}
                                </label>
                                <InputNumber
                                    value={!isEmpty(data.amountAccepted) && data.amountAccepted > 0 ? data.amountAccepted : data.amountRequested}
                                    maxFractionDigits={2}
                                    readOnly={!isEmpty(data.amountAccepted) && data.amountAccepted > 0}
                                    invalid={!finalDialogData.amount || isEmpty(finalDialogData.amount) || finalDialogData.amount === 0}
                                    onChange={(e) => updateFinalDialogData(e.value, 'amount')}/>
                            </div> : null}
                        {operationType === 'reject' && APP_HUB_ID !== 't7jh5wfg9QXylNaTZkPoE'
                            ? <div className="appForm__field">
                                <label
                                    className={classNames({ 'p-error': !finalDialogData.reason || isEmpty(finalDialogData.reason) })}>
                                    {__('Oggetto', 'gepafin')}
                                </label>
                                <Dropdown
                                    value={rejectionReasons.find(reason => reason.id === finalDialogData.reasonId) || null}
                                    options={rejectionReasons}
                                    optionLabel="label"
                                    placeholder={__('Seleziona motivo', 'gepafin')}
                                    onChange={(e) => {
                                        setFinalDialogData(prev => ({
                                            ...prev,
                                            reasonId: e.value.id,
                                            reason: e.value.text,
                                            subject: e.value.subject
                                        }))
                                    }}
                                    style={{ marginBottom: '10px' }}
                                />
                                <InputTextarea
                                    name="reason"
                                    value={finalDialogData.reason}
                                    invalid={!finalDialogData.reason || isEmpty(finalDialogData.reason)}
                                    onChange={(e) => updateFinalDialogData(e.target.value, 'reason')}
                                    rows={3}
                                    style={{ width: '100%' }}/>
                            </div> : null}
                        <div className="appForm__field">
                            <label>
                                {__('Motivazione', 'gepafin')}
                            </label>
                            <div translate="no">
                                <Editor
                                    value={finalDialogData.motivation}
                                    readOnly={loading}
                                    placeholder={__('Digita qui il messagio', 'gepafin')}
                                    headerTemplate={header}
                                    onTextChange={(e) => updateFinalDialogData(e.htmlValue, 'motivation')}
                                    style={{ height: 80 * 3, width: '100%' }}
                                />
                            </div>
                        </div>
                        {operationType === 'reject' && APP_HUB_ID !== 't7jh5wfg9QXylNaTZkPoE'
                            ? <div className="appForm__field">
                                <label>
                                    {__('Files', 'gepafin')}
                                </label>
                                <FileUpload
                                    ref={finalDialogFilesRef}
                                    name="files[]"
                                    multiple
                                    accept={mimeTypes.map(o => o.code).join(',')}
                                    maxFileSize={defaultMaxFileSize}
                                    auto={false}
                                    customUpload={true}
                                    onSelect={(e) => {
                                        updateFinalDialogData(e.files, 'files');
                                    }}
                                    onRemove={(e) => {
                                        const updatedFiles = finalDialogFilesRef.current.getFiles();
                                        updateFinalDialogData(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) => {
                                        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> : null}
                    </Dialog>

                    <Dialog
                        visible={isVisibleAppointmentDialog}
                        modal
                        header={headerAppointmentDialog}
                        footer={footerAppointmentDialog}
                        style={{ maxWidth: '600px', width: '100%' }}
                        onHide={hideAppointmentDialog}>
                        <div className="appForm__field">
                            <label
                                className={classNames({ 'p-error': isEmpty(appointmentData.amount) || appointmentData.amount === 0 })}>
                                {__('Importo', 'gepafin')}
                            </label>
                            <InputNumber
                                value={appointmentData.amount}
                                locale="it-IT"
                                minFractionDigits={2}
                                invalid={isEmpty(appointmentData.amount) || appointmentData.amount === 0}
                                onChange={(e) => setAppointmentFieldValue('amount', e.value)}/>
                        </div>
                        <div className="appForm__field">
                            <label
                                className={classNames({ 'p-error': isEmpty(appointmentData.duration) || appointmentData.duration === 0 })}>
                                {__('Durata', 'gepafin')}
                            </label>
                            <InputNumber
                                value={appointmentData.duration}
                                keyfilter="int"
                                invalid={isEmpty(appointmentData.duration) || appointmentData.duration === 0}
                                onChange={(e) => setAppointmentFieldValue('duration', e.value)}/>
                        </div>
                        <div className="appForm__field">
                            <label className={classNames({ 'p-error': isEmpty(appointmentData.title) })}>
                                {__('Titolo', 'gepafin')}
                            </label>
                            <InputText
                                value={appointmentData.title}
                                invalid={isEmpty(appointmentData.title)}
                                onChange={(e) => setAppointmentFieldValue('title', e.target.value)}/>
                        </div>
                        <div className="appForm__field">
                            <label className={classNames({ 'p-error': isEmpty(appointmentData.text) })}>
                                {__('Messaggio', 'gepafin')}
                            </label>
                            <InputTextarea
                                value={appointmentData.text}
                                invalid={isEmpty(appointmentData.text)}
                                onChange={(e) => setAppointmentFieldValue('text', e.target.value)}
                                rows={3}
                                cols={30}/>
                        </div>
                    </Dialog>

                    <Dialog
                        visible={isVisiblePreTecEvalDialog}
                        modal
                        header={headerPreTecEvalDialog}
                        footer={footerPreTecEvalDialog}
                        style={{ maxWidth: '600px', width: '100%' }}
                        onHide={hidePreTecEvalDialog}>
                        {preTecEvalData.amendmentDocumentType === 'BLUE_TONGUE'
                            ? <>
                                <div className="appForm__field">
                                    <label
                                        className={classNames({
                                            'p-error': isNil(preTecEvalData.blueTongueField1)
                                                || isNaN(parseFloat(preTecEvalData.blueTongueField1))
                                        })}>
                                        {__('Indenizzo per morti capi', 'gepafin')}
                                    </label>
                                    <InputNumber
                                        value={preTecEvalData.blueTongueField1}
                                        locale="it-IT"
                                        minFractionDigits={2}
                                        invalid={isNil(preTecEvalData.blueTongueField1)
                                            || isNaN(parseFloat(preTecEvalData.blueTongueField1))}
                                        onChange={(e) => setBlueTongueFieldValue('blueTongueField1', e.value)}/>
                                </div>
                                <div className="appForm__field">
                                    <label
                                        className={classNames({
                                            'p-error': isNil(preTecEvalData.blueTongueField2)
                                                || isNaN(parseFloat(preTecEvalData.blueTongueField2))
                                        })}>
                                        {__('Indenizzo per smaltimento', 'gepafin')}
                                    </label>
                                    <InputNumber
                                        value={preTecEvalData.blueTongueField2}
                                        locale="it-IT"
                                        minFractionDigits={2}
                                        invalid={isNil(preTecEvalData.blueTongueField2)
                                            || isNaN(parseFloat(preTecEvalData.blueTongueField2))}
                                        onChange={(e) => setBlueTongueFieldValue('blueTongueField2', e.value)}/>
                                </div>
                                <div className="appForm__field">
                                    <label>{__('Indenizzo totale', 'gepafin')}</label>
                                    <InputNumber
                                        value={preTecEvalData.amount}
                                        locale="it-IT"
                                        minFractionDigits={2}
                                        disabled/>
                                </div>
                            </>
                            : <div className="appForm__field">
                                <label
                                    className={classNames({
                                        'p-error': isEmpty(preTecEvalData.amount)
                                            || isNaN(parseFloat(preTecEvalData.amount)) || parseFloat(preTecEvalData.amount) <= 0
                                    })}>
                                    {__('Importo', 'gepafin')}
                                </label>
                                <InputNumber
                                    value={preTecEvalData.amount}
                                    locale="it-IT"
                                    minFractionDigits={2}
                                    invalid={isEmpty(preTecEvalData.amount) || isNaN(parseFloat(preTecEvalData.amount)) || parseFloat(preTecEvalData.amount) <= 0}
                                    onChange={(e) => setPreTecEvalFieldValue('amount', e.value)}/>
                            </div>
                        }
                    </Dialog>
                </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>
    )

}

export default DomandaEditInstructorManager;
