import React, { useState, useRef, useCallback } from 'react';
import { __ } from '@wordpress/i18n';

// api
import AdminService from '../../../../service/admin-service';

// components
import { InputText } from 'primereact/inputtext';
import { InputTextarea } from 'primereact/inputtextarea';
import { Button } from 'primereact/button';
import { Toast } from 'primereact/toast';

const ManageSendPecSection = () => {
    const [subject, setSubject] = useState('');
    const [body, setBody] = useState('');
    const [csvFile, setCsvFile] = useState(null);
    const [attachment, setAttachment] = useState(null);
    const [localAsyncRequest, setLocalAsyncRequest] = useState(false);
    const toast = useRef(null);
    const csvInputRef = useRef(null);
    const attachmentInputRef = useRef(null);

    const isSubmitDisabled = localAsyncRequest || !subject.trim() || !body.trim() || !csvFile;

    const handleSubmit = useCallback(() => {
        const formData = new FormData();
        formData.append('subject', subject);
        formData.append('body', body);
        formData.append('csv_file', csvFile);
        if (attachment) {
            formData.append('attachment', attachment);
        }

        setLocalAsyncRequest(true);
        AdminService.doSendPec(
            formData,
            (resp) => {
                setLocalAsyncRequest(false);
                if (resp && resp.status === 'ok') {
                    const detail = resp.data
                        ? __(`Invio completato: ${resp.data.total_sent} inviati, ${resp.data.total_errors} errori`, 'gepafin')
                        : __('Invio completato con successo', 'gepafin');
                    if (toast.current) {
                        toast.current.show({ severity: 'success', summary: '', detail });
                    }
                    setSubject('');
                    setBody('');
                    setCsvFile(null);
                    setAttachment(null);
                    if (csvInputRef.current) csvInputRef.current.value = '';
                    if (attachmentInputRef.current) attachmentInputRef.current.value = '';
                } else {
                    if (toast.current) {
                        toast.current.show({ severity: 'error', summary: '', detail: resp && resp.detail ? resp.detail : __('Errore durante l\'invio', 'gepafin') });
                    }
                }
            },
            (resp) => {
                setLocalAsyncRequest(false);
                if (toast.current) {
                    toast.current.show({ severity: 'error', summary: '', detail: resp && resp.detail ? resp.detail : __('Errore durante l\'invio', 'gepafin') });
                }
            }
        );
    }, [subject, body, csvFile, attachment]);

    return (
        <div className="appPageSection">
            <h2>{__('Invio PEC Massivo', 'gepafin')}</h2>
            <Toast ref={toast}/>
            <div className="appForm">
                <div className="appForm__field">
                    <label htmlFor="pecSubject">{__('Oggetto', 'gepafin')} *</label>
                    <InputText
                        id="pecSubject"
                        value={subject}
                        onChange={(e) => setSubject(e.target.value)}
                        style={{ width: '100%' }}/>
                </div>
                <div className="appForm__field">
                    <label htmlFor="pecBody">{__('Corpo della PEC', 'gepafin')} *</label>
                    <InputTextarea
                        id="pecBody"
                        value={body}
                        onChange={(e) => setBody(e.target.value)}
                        rows={8}
                        style={{ width: '100%' }}/>
                </div>
                <div className="appForm__field">
                    <label htmlFor="pecCsv">{__('File CSV destinatari', 'gepafin')} *</label>
                    <input
                        ref={csvInputRef}
                        id="pecCsv"
                        type="file"
                        accept=".csv"
                        onChange={(e) => setCsvFile(e.target.files[0] || null)}/>
                    <small>{__('Il file CSV deve contenere gli indirizzi PEC nella prima colonna', 'gepafin')}</small>
                </div>
                <div className="appForm__field">
                    <label htmlFor="pecAttachment">{__('Allegato (opzionale)', 'gepafin')}</label>
                    <input
                        ref={attachmentInputRef}
                        id="pecAttachment"
                        type="file"
                        onChange={(e) => setAttachment(e.target.files[0] || null)}/>
                </div>
                <div className="appPageSection__actions">
                    <Button
                        type="button"
                        label={__('Invia PEC', 'gepafin')}
                        icon="pi pi-send"
                        loading={localAsyncRequest}
                        disabled={isSubmitDisabled}
                        onClick={handleSubmit}/>
                </div>
            </div>
        </div>
    );
};

export default ManageSendPecSection;
