import React, { useState, useRef } from 'react';
import { __ } from '@wordpress/i18n';
import { useNavigate } from 'react-router-dom';

import { Card } from 'primereact/card';
import { Button } from 'primereact/button';
import { InputText } from 'primereact/inputtext';
import { Toast } from 'primereact/toast';

import { storeSet } from '../../../store';
import RendicontazioneService from '../service/rendicontazioneService';


/**
 * Pagina sandbox: permette al superadmin di impersonare un altro utente
 * (tipicamente beneficiario) senza passare per SPID. Solo per sviluppo.
 */
const DevSwitchUser = () => {
    const navigate = useNavigate();
    const toast = useRef(null);
    const [email, setEmail] = useState('beneficiario@sandbox.local');
    const [loading, setLoading] = useState(false);

    const doImpersonate = () => {
        setLoading(true);
        RendicontazioneService.impersonate(email,
            (resp) => {
                const data = resp?.data;
                if (!data?.token) {
                    toast.current?.show({ severity: 'error', summary: __('Risposta vuota', 'gepafin') });
                    setLoading(false);
                    return;
                }
                // popola lo store Zustand come dopo il login
                storeSet('setAuthData', {
                    token: data.token,
                    userData: data.user
                });
                toast.current?.show({ severity: 'success', summary: __('Ora sei ', 'gepafin') + data.user.email });
                // aspetta un tick e ricarica a root
                setTimeout(() => window.location.replace('/'), 700);
            },
            (err) => {
                toast.current?.show({ severity: 'error', summary: __('Impersonate fallito', 'gepafin'), detail: err?.detail });
                setLoading(false);
            }
        );
    };

    return (
        <div className="appPage">
            <Toast ref={toast} />
            <div className="appPage__pageHeader">
                <h1>{__('Dev: cambia utente', 'gepafin')}</h1>
                <p>{__('Pagina sandbox. Permette di impersonare un utente (es. beneficiario) senza passare per SPID.', 'gepafin')}</p>
            </div>

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

            <div className="appPageSection">
                <Card style={{ width: '100%', maxWidth: '500px' }}>
                    <form className="appForm p-fluid" onSubmit={(e) => { e.preventDefault(); doImpersonate(); }}>
                        <div className="appForm__field">
                            <label>{__('Email utente da impersonare', 'gepafin')}</label>
                            <InputText value={email} onChange={(e) => setEmail(e.target.value)} />
                            <small className="text-color-secondary">
                                {__('Prova: beneficiario@sandbox.local oppure admin@sandbox.local', 'gepafin')}
                            </small>
                        </div>
                        <div style={{ marginTop: '1rem', display: 'flex', gap: '0.75rem' }}>
                            <Button type="button" outlined label={__('Indietro', 'gepafin')}
                                onClick={() => navigate('/')} />
                            <Button type="submit" label={__('Impersona', 'gepafin')} icon="pi pi-user-edit"
                                loading={loading} severity="warning" />
                        </div>
                    </form>
                </Card>
            </div>
        </div>
    );
};

export default DevSwitchUser;
