import React, { useMemo, useRef } from 'react';
import { __ } from '@wordpress/i18n';
import { useForm } from 'react-hook-form';

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

// components
import set404FromErrorResponse from '../../helpers/set404FromErrorResponse';
import FormField from '../../components/FormField';
import { Button } from 'primereact/button';
import { Toast } from 'primereact/toast';

// api
import UserService from '../../service/user-service';

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

const Profile = () => {
    const isAsyncRequest = useStoreValue('isAsyncRequest');
    const userData = useStoreValue('userData');
    const toast = useRef(null);

    const {
        control,
        handleSubmit,
        formState: { errors }
    } = useForm({
        defaultValues: useMemo(() => {
            return userData;
        }, [userData]),
        mode: 'onChange'
    });

    const onSubmit = (formData) => {
        storeSet('setAsyncRequest');

        UserService.updateUserSelf(userData.id, formData, updateCallback, updateError);
    };

    const updateCallback = (data) => {
        if (data.status === 'SUCCESS') {
            storeSet('userData', data.data);
            if (toast.current) {
                toast.current.show({
                    severity: 'success',
                    summary: '',
                    detail: __('L\'utente è stato aggiornato!', 'gepafin')
                });
            }
        }
        storeSet('unsetAsyncRequest');
    }

    const updateError = (data) => {
        set404FromErrorResponse(data);
        storeSet('unsetAsyncRequest');
    }

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

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

            <form className="appForm" onSubmit={handleSubmit(onSubmit)}>

                <div className="appPageSection">
                    <h2>{__('Informazioni personali', 'gepafin')}</h2>
                    <div className="appForm__cols">
                        <FormField
                            type="textinput"
                            disabled={true}
                            fieldName="firstName"
                            label={__('Nome', 'gepafin')}
                            control={control}
                            errors={errors}
                            config={{ required: __('È obbligatorio', 'gepafin') }}
                            placeholder="Francesco"
                        />

                        <FormField
                            type="textinput"
                            disabled={true}
                            fieldName="lastName"
                            label={__('Cognome', 'gepafin')}
                            control={control}
                            errors={errors}
                            config={{ required: __('È obbligatorio', 'gepafin') }}
                            placeholder="Moli"
                        />

                        <FormField
                            type="textinput"
                            disabled={true}
                            fieldName="codiceFiscale"
                            label={__('Codice fiscale', 'gepafin')}
                            control={control}
                            errors={errors}
                            config={{ required: __('È obbligatorio', 'gepafin') }}
                            placeholder="XXXXXXXX"
                        />
                    </div>
                    <div className="appForm__cols">
                        <FormField
                            type="textinput"
                            fieldName="email"
                            disabled={true}
                            label={__('Email', 'gepafin')}
                            control={control}
                            errors={errors}
                            config={{ required: __('È obbligatorio', 'gepafin') }}
                            placeholder="user@example.com"
                        />

                        <FormField
                            type="textinput"
                            fieldName="phoneNumber"
                            label={__('Telefono', 'gepafin')}
                            control={control}
                            errors={errors}
                            config={{ required: __('È obbligatorio', 'gepafin') }}
                            placeholder="1234567"
                        />
                    </div>
                </div>

                <div className="appPageSection">
                    <h2>{__('Impostazioni', 'gepafin')}</h2>
                    <div className="appForm__cols">
                        <FormField
                            type="select"
                            disabled={true}
                            fieldName="language"
                            defaultValue={'it'}
                            label={__('Lingua predefinita', 'gepafin')}
                            control={control}
                            errors={errors}
                            config={{ required: __('È obbligatorio', 'gepafin') }}
                            options={[
                                { label: __('Italiano', 'gepafin'), name: 'it' }
                            ]}
                        />

                        <FormField
                            type="select"
                            disabled={true}
                            fieldName="timezone"
                                defaultValue={'Europe/Rome'}
                                label={__('Fuso Orario', 'gepafin')}
                                control={control}
                                errors={errors}
                                config={{ required: __('È obbligatorio', 'gepafin') }}
                                options={[
                                    { label: __('Europe/Rome', 'gepafin'), name: 'Europe/Rome' }
                                ]}
                            />

                            <FormField
                                type="select"
                                disabled={true}
                                fieldName="dateformat"
                                defaultValue={'DD/MM/YY'}
                                label={__('Formato Data', 'gepafin')}
                                control={control}
                                errors={errors}
                                config={{ required: __('È obbligatorio', 'gepafin') }}
                                options={[
                                    { label: __('DD/MM/YY', 'gepafin'), name: 'DD/MM/YY' }
                                ]}
                            />
                        </div>
                    </div>

                    <div className="appPageSection">
                        <h2>{__('Sicurezza', 'gepafin')}</h2>
                        <div className="appForm__row">
                            <label>{__('Ultimo accesso', 'gepafin')}</label>
                            <span>{getDateFromISOstring(userData.lastLogin)}</span>
                        </div>
                    </div>

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

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

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

                    <div className="appPageSection">
                        <div className="appPageSection__actions">
                            <Button
                                disabled={isAsyncRequest}
                                label={__('Salva modifiche', 'gepafin')}
                                icon="pi pi-check" iconPos="right"/>
                        </div>
                    </div>
            </form>

        </div>
)

}

export default Profile;