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

import { Card } from 'primereact/card';
import { Button } from 'primereact/button';
import { Toast } from 'primereact/toast';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { ConfirmDialog, confirmDialog } from 'primereact/confirmdialog';
import { Dropdown } from 'primereact/dropdown';
import { Dialog } from 'primereact/dialog';

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

import Ar1Service from '../service/ar1Service';
import Ar1StatusTag from '../components/Ar1StatusTag';

const VARIANT_OPTIONS = [
    { label: 'A1 — Persona Giuridica (societa, ente)', value: 'A1' },
    { label: 'A2 — Ditta Individuale (P.IVA persona fisica)', value: 'A2' },
    { label: 'A3 — Persona Fisica (senza P.IVA)', value: 'A3' },
];

/**
 * Ar1Home: schermata principale modulo AR1 per il beneficiario.
 * - Card status con countdown
 * - CTA dinamici (Compila / Riprendi / Firma / Rinnova)
 * - Storico dichiarazioni
 */
const Ar1Home = () => {
    const navigate = useNavigate();
    const toast = useRef(null);
    const companyId = useStoreValue('chosenCompanyId');

    const [status, setStatus] = useState(null);
    const [history, setHistory] = useState([]);
    const [loading, setLoading] = useState(true);
    const [variantDialogOpen, setVariantDialogOpen] = useState(false);
    const [selectedVariant, setSelectedVariant] = useState('A1');
    const [creating, setCreating] = useState(false);

    const loadAll = () => {
        if (!companyId) return;
        setLoading(true);
        Ar1Service.getStatusForCompany(companyId,
            (resp) => setStatus(resp),
            (err) => console.warn('getStatus failed', err)
        );
        Ar1Service.listFormsForCompany(companyId,
            (resp) => {
                setHistory(resp?.items || []);
                setLoading(false);
            },
            (err) => {
                setLoading(false);
                if (toast.current) toast.current.show({ severity: 'error', summary: 'Errore', detail: err?.detail || 'Impossibile caricare lo storico' });
            }
        );
    };

    useEffect(() => {
        loadAll();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [companyId]);

    const startNewDraft = () => {
        setCreating(true);
        Ar1Service.createDraft(companyId, selectedVariant,
            (resp) => {
                setCreating(false);
                setVariantDialogOpen(false);
                if (resp?.id) navigate(`/ar1/wizard/${resp.id}`);
            },
            (err) => {
                setCreating(false);
                if (toast.current) toast.current.show({ severity: 'error', summary: 'Errore', detail: err?.detail || 'Impossibile creare il form' });
            }
        );
    };

    const resumeForm = (formId) => navigate(`/ar1/wizard/${formId}`);
    const goToSignature = (formId) => navigate(`/ar1/signature/${formId}`);

    const deleteDraft = (formId) => {
        confirmDialog({
            message: __('Sei sicuro di voler eliminare questa bozza? L\'operazione non puo essere annullata.', 'gepafin'),
            header: __('Conferma eliminazione', 'gepafin'),
            icon: 'pi pi-exclamation-triangle',
            acceptLabel: __('Elimina', 'gepafin'),
            rejectLabel: __('Annulla', 'gepafin'),
            acceptClassName: 'p-button-danger',
            accept: () => {
                Ar1Service.deleteForm(formId,
                    () => {
                        if (toast.current) toast.current.show({ severity: 'success', summary: 'OK', detail: 'Bozza eliminata' });
                        loadAll();
                    },
                    (err) => {
                        if (toast.current) toast.current.show({ severity: 'error', summary: 'Errore', detail: err?.detail || 'Eliminazione fallita' });
                    }
                );
            }
        });
    };

    const renderStatusCard = () => {
        if (!status) return null;
        const isUrgent = ['MISSING', 'EXPIRED'].includes(status.status);
        const canCompile = ['MISSING', 'EXPIRED', 'APPROACHING', 'VALID'].includes(status.status);
        const hasActive = status.form_id && ['DRAFT', 'AWAITING_SIGNATURE'].includes(status.status);

        return (
            <Card title={__('Stato Dichiarazione AR1 — Adeguata Verifica', 'gepafin')} style={{ marginBottom: 20 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
                    <Ar1StatusTag status={status.status} />
                    {status.variant && (
                        <span style={{ color: '#666' }}>
                            {__('Variante:', 'gepafin')} <strong>{status.variant}</strong>
                        </span>
                    )}
                    {status.days_to_expiry !== null && status.days_to_expiry !== undefined && (
                        <span style={{ color: isUrgent ? '#b71c1c' : '#444', fontWeight: 600 }}>
                            {status.days_to_expiry < 0
                                ? __(`Scaduta da ${Math.abs(status.days_to_expiry)} giorni`, 'gepafin')
                                : __(`Scade tra ${status.days_to_expiry} giorni`, 'gepafin')}
                        </span>
                    )}
                </div>

                {status.must_recompile_reason && (
                    <div style={{ marginTop: 12, padding: 10, background: '#fff3e0', borderLeft: '3px solid #e65100' }}>
                        <i className="pi pi-info-circle" style={{ marginRight: 6 }} />
                        {status.must_recompile_reason}
                    </div>
                )}

                <div style={{ marginTop: 16, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                    {hasActive && status.status === 'DRAFT' && (
                        <Button label={__('Riprendi compilazione', 'gepafin')} icon="pi pi-pencil" onClick={() => resumeForm(status.form_id)} />
                    )}
                    {hasActive && status.status === 'AWAITING_SIGNATURE' && (
                        <Button label={__('Procedi alla firma', 'gepafin')} icon="pi pi-verified" severity="warning" onClick={() => goToSignature(status.form_id)} />
                    )}
                    {!hasActive && canCompile && (
                        <Button
                            label={status.status === 'MISSING' ? __('Compila adesso', 'gepafin') : __('Rinnova dichiarazione', 'gepafin')}
                            icon="pi pi-plus"
                            onClick={() => setVariantDialogOpen(true)}
                        />
                    )}
                </div>
            </Card>
        );
    };

    const statusTpl = (row) => <Ar1StatusTag status={row.status} />;
    const dateTpl = (row, field) => {
        const v = row[field];
        if (!v) return '—';
        try { return new Date(v).toLocaleDateString('it-IT'); } catch (e) { return v; }
    };
    const actionsTpl = (row) => (
        <div style={{ display: 'flex', gap: 4 }}>
            {row.status === 'DRAFT' && (
                <>
                    <Button icon="pi pi-pencil" rounded text onClick={() => resumeForm(row.id)} tooltip={__('Riprendi', 'gepafin')} />
                    <Button icon="pi pi-trash" rounded text severity="danger" onClick={() => deleteDraft(row.id)} tooltip={__('Elimina', 'gepafin')} />
                </>
            )}
            {row.status === 'AWAITING_SIGNATURE' && (
                <Button icon="pi pi-verified" rounded text severity="warning" onClick={() => goToSignature(row.id)} tooltip={__('Firma', 'gepafin')} />
            )}
            {['SIGNED', 'VERIFIED', 'EXPIRED'].includes(row.status) && (
                <Button icon="pi pi-download" rounded text onClick={async () => {
                    try {
                        const blob = await Ar1Service.downloadPdfSigned(row.id);
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = `AR1_${row.variant}_signed.pdf`;
                        a.click();
                        URL.revokeObjectURL(url);
                    } catch (e) {
                        if (toast.current) toast.current.show({ severity: 'error', summary: 'Errore', detail: e.message });
                    }
                }} tooltip={__('Scarica firmato', 'gepafin')} />
            )}
        </div>
    );

    return (
        <div style={{ padding: 16 }}>
            <Toast ref={toast} />
            <ConfirmDialog />

            <h1>{__('Dichiarazione AR1 — Adeguata Verifica', 'gepafin')}</h1>
            <p style={{ color: '#666' }}>
                {__('Modulo di aggiornamento dell\'adeguata verifica ai sensi del D.Lgs. 231/2007 (normativa antiriciclaggio).', 'gepafin')}
            </p>

            {renderStatusCard()}

            <Card title={__('Storico dichiarazioni', 'gepafin')}>
                <DataTable
                    value={history}
                    loading={loading}
                    emptyMessage={__('Nessuna dichiarazione presente', 'gepafin')}
                    paginator={history.length > 10}
                    rows={10}
                >
                    <Column field="variant" header={__('Variante', 'gepafin')} />
                    <Column field="template_version" header={__('Versione modulo', 'gepafin')} />
                    <Column field="status" header={__('Stato', 'gepafin')} body={statusTpl} />
                    <Column field="created_at" header={__('Creato il', 'gepafin')} body={(r) => dateTpl(r, 'created_at')} />
                    <Column field="signed_at" header={__('Firmato il', 'gepafin')} body={(r) => dateTpl(r, 'signed_at')} />
                    <Column field="expires_at" header={__('Scade il', 'gepafin')} body={(r) => dateTpl(r, 'expires_at')} />
                    <Column header={__('Azioni', 'gepafin')} body={actionsTpl} style={{ width: 160 }} />
                </DataTable>
            </Card>

            <Dialog
                header={__('Scegli tipologia', 'gepafin')}
                visible={variantDialogOpen}
                onHide={() => setVariantDialogOpen(false)}
                style={{ width: '480px', maxWidth: '95vw' }}
                modal
            >
                <p style={{ marginBottom: 10 }}>
                    {__('Seleziona la tipologia di soggetto che rappresenti:', 'gepafin')}
                </p>
                <Dropdown
                    value={selectedVariant}
                    options={VARIANT_OPTIONS}
                    onChange={(e) => setSelectedVariant(e.value)}
                    style={{ width: '100%', marginBottom: 16 }}
                />
                <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                    <Button label={__('Annulla', 'gepafin')} severity="secondary" outlined onClick={() => setVariantDialogOpen(false)} />
                    <Button label={__('Inizia compilazione', 'gepafin')} icon="pi pi-arrow-right" iconPos="right" loading={creating} onClick={startNewDraft} />
                </div>
            </Dialog>
        </div>
    );
};

export default Ar1Home;
