import React, { useEffect, useState, useMemo } from 'react';
import { __ } from '@wordpress/i18n';
import { Dialog } from 'primereact/dialog';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Button } from 'primereact/button';
import { Tag } from 'primereact/tag';
import { InputText } from 'primereact/inputtext';
import { Dropdown } from 'primereact/dropdown';
import { Skeleton } from 'primereact/skeleton';
import { Message } from 'primereact/message';

import CompanyDocumentsService from '../../../service/company-documents-service';

/**
 * Modal per scegliere un documento dal repository della company.
 *
 * Carica tramite 2 chiamate al BE Spring:
 *  - default (no filter)   -> COMPANY_DOCUMENT + APPLICATION_DOCUMENT
 *  - documentType=PERSONAL -> PERSONAL_DOCUMENT (amministratore/legale rappresentante)
 *
 * Unione dei risultati e deduplicazione per document_category_id scegliendo
 * il piu recente attivo (VALID > DUE, a parita id desc). Questo mitiga il
 * fatto che il BE Gepafin non implementa sostituzione automatica su upload
 * stessa categoria (es. 2 DURC attivi in DB).
 *
 * Props:
 *   visible, companyId, onHide, onSelect(doc), currentSourceId
 */
const STATUS_CFG = {
    VALID:   { severity: 'success', label: 'Valido',      icon: 'pi pi-check-circle' },
    DUE:     { severity: 'warning', label: 'In scadenza', icon: 'pi pi-exclamation-triangle' },
    EXPIRED: { severity: 'danger',  label: 'Scaduto',     icon: 'pi pi-times-circle' },
};

const ORIGIN_CFG = {
    COMPANY_DOCUMENT:     { label: 'Azienda',       icon: 'pi pi-building', color: 'var(--blue-500)',   bg: 'var(--blue-50)' },
    PERSONAL_DOCUMENT:    { label: 'Amministratore', icon: 'pi pi-user',     color: 'var(--purple-500)', bg: 'var(--purple-50)' },
    APPLICATION_DOCUMENT: { label: 'Applicazione',   icon: 'pi pi-file',     color: 'var(--teal-500)',   bg: 'var(--teal-50)' },
};

const formatDate = (d) => {
    if (!d) return '—';
    try { return new Date(d).toLocaleDateString('it-IT', { day: '2-digit', month: '2-digit', year: 'numeric' }); }
    catch { return String(d); }
};
const daysUntil = (d) => { if (!d) return null; try { return Math.ceil((new Date(d).getTime() - Date.now()) / 86400000); } catch { return null; } };
const getCategoryName = (d) => (d.category && d.category.categoryName) || d.type || '—';
const getOriginType = (d) => d.type || 'COMPANY_DOCUMENT';

// dedup: per ogni (type + category), mantieni il piu recente attivo. VALID > DUE, poi id desc
const dedupByCategory = (docs) => {
    const STATUS_RANK = { VALID: 0, DUE: 1, EXPIRED: 2 };
    const groups = new Map();
    for (const d of docs) {
        const key = `${d.type || 'X'}::${getCategoryName(d)}`;
        const rank = (STATUS_RANK[d.status] ?? 99) * 1e12 - (d.id || 0);
        const prev = groups.get(key);
        if (!prev || rank < prev._rank) {
            groups.set(key, { ...d, _rank: rank });
        }
    }
    return Array.from(groups.values()).map(({ _rank, ...rest }) => rest);
};

const CompanyDocumentPicker = ({ visible, companyId, onHide, onSelect, currentSourceId = null }) => {
    const [loading, setLoading] = useState(false);
    const [docs, setDocs] = useState([]);
    const [error, setError] = useState(null);

    const [selectedId, setSelectedId] = useState(null);
    const [search, setSearch] = useState('');
    const [categoryFilter, setCategoryFilter] = useState(null);
    const [statusFilter, setStatusFilter] = useState(null);
    const [originFilter, setOriginFilter] = useState('ALL'); // ALL | COMPANY_DOCUMENT | PERSONAL_DOCUMENT

    useEffect(() => {
        if (!visible || !companyId) return;
        setLoading(true);
        setError(null);
        setSelectedId(currentSourceId);
        setSearch(''); setCategoryFilter(null); setStatusFilter(null); setOriginFilter('ALL');

        // doppia chiamata: company/application + personal
        let collected = [];
        let pending = 2;
        const done = () => { if (--pending === 0) { setDocs(dedupByCategory(collected)); setLoading(false); } };

        CompanyDocumentsService.getCompanyDocuments(
            companyId,
            (resp) => { if (resp?.status === 'SUCCESS') collected = collected.concat(resp.data || []); done(); },
            () => { setError(__('Impossibile caricare i documenti del repository.', 'gepafin')); done(); }
        );
        CompanyDocumentsService.getCompanyDocuments(
            companyId,
            (resp) => { if (resp?.status === 'SUCCESS') collected = collected.concat(resp.data || []); done(); },
            () => done(),
            [['documentType', 'PERSONAL_DOCUMENT']]
        );
    }, [visible, companyId, currentSourceId]);

    // opzioni filtri derivate
    const categoryOptions = useMemo(() => Array.from(new Set(docs.map(getCategoryName).filter(Boolean))).sort().map(t => ({ label: t, value: t })), [docs]);
    const statusOptions = [
        { label: __('Validi', 'gepafin'),      value: 'VALID' },
        { label: __('In scadenza', 'gepafin'), value: 'DUE' },
    ];

    const filteredDocs = useMemo(() => {
        const s = (search || '').trim().toLowerCase();
        return docs.filter(d => {
            if (originFilter !== 'ALL' && getOriginType(d) !== originFilter) return false;
            if (categoryFilter && getCategoryName(d) !== categoryFilter) return false;
            if (statusFilter && d.status !== statusFilter) return false;
            if (s) {
                const hay = [d.fileName, d.name, getCategoryName(d)].filter(Boolean).join(' ').toLowerCase();
                if (!hay.includes(s)) return false;
            }
            return true;
        });
    }, [docs, search, categoryFilter, statusFilter, originFilter]);

    // templates colonne
    const nameTpl = (row) => (
        <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                <i className="pi pi-file-pdf" style={{ color: 'var(--primary-color)', fontSize: '1.1rem' }} />
                <strong style={{ fontSize: '0.95rem' }}>{row.fileName || row.name || `Doc #${row.id}`}</strong>
            </div>
            {row.name && row.name !== row.fileName && (
                <div style={{ marginLeft: '1.6rem' }}><small className="text-color-secondary">{row.name}</small></div>
            )}
        </div>
    );
    const originTpl = (row) => {
        const cfg = ORIGIN_CFG[getOriginType(row)] || ORIGIN_CFG.COMPANY_DOCUMENT;
        return (
            <span style={{
                display: 'inline-flex', alignItems: 'center', gap: '0.35rem',
                background: cfg.bg, color: cfg.color, padding: '0.2rem 0.6rem',
                borderRadius: '12px', fontSize: '0.8rem', fontWeight: 500
            }}>
                <i className={cfg.icon} style={{ fontSize: '0.8rem' }} />
                {cfg.label}
            </span>
        );
    };
    const categoryTpl = (row) => (
        <Tag value={getCategoryName(row)} severity="secondary"
             style={{ fontFamily: 'monospace', fontSize: '0.8rem' }} />
    );
    const statusTpl = (row) => {
        const cfg = STATUS_CFG[row.status] || { severity: 'secondary', label: row.status || '—', icon: 'pi pi-question' };
        const days = daysUntil(row.expirationDate);
        return (
            <div>
                <Tag severity={cfg.severity} icon={cfg.icon} value={cfg.label} style={{ fontWeight: 600 }} />
                {row.status === 'DUE' && days != null && days >= 0 && (
                    <div><small className="text-color-secondary">scade tra {days} {days === 1 ? 'giorno' : 'giorni'}</small></div>
                )}
            </div>
        );
    };
    const expiryTpl = (row) => <div style={{ fontFamily: 'monospace', fontSize: '0.9rem' }}>{formatDate(row.expirationDate)}</div>;

    const chosenDoc = useMemo(() => docs.find(d => d.id === selectedId) || null, [docs, selectedId]);

    const footer = (
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%', gap: '1rem' }}>
            <div style={{ flex: 1, minWidth: 0 }}>
                {chosenDoc ? (
                    <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', flexWrap: 'wrap' }}>
                        <small className="text-color-secondary">{__('Selezionato', 'gepafin')}:</small>
                        <strong style={{ fontSize: '0.9rem' }}>{chosenDoc.fileName || chosenDoc.name}</strong>
                        <Tag severity={(STATUS_CFG[chosenDoc.status]||{}).severity || 'secondary'}
                             icon={(STATUS_CFG[chosenDoc.status]||{}).icon}
                             value={(STATUS_CFG[chosenDoc.status]||{}).label || chosenDoc.status} />
                    </div>
                ) : (
                    <small className="text-color-secondary">{__('Seleziona una riga per continuare', 'gepafin')}</small>
                )}
            </div>
            <div style={{ display: 'flex', gap: '0.5rem', flexShrink: 0 }}>
                <Button label={__('Annulla', 'gepafin')} severity="secondary" text onClick={onHide} />
                <Button label={__('Seleziona', 'gepafin')} icon="pi pi-check" disabled={!chosenDoc}
                    onClick={() => { if (chosenDoc) { onSelect(chosenDoc); onHide(); } }} />
            </div>
        </div>
    );

    const dialogHeader = (
        <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
            <i className="pi pi-folder-open" style={{ color: 'var(--primary-color)', fontSize: '1.3rem' }} />
            <span>{__('Scegli dal repository aziendale', 'gepafin')}</span>
            {!loading && !error && (
                <small className="text-color-secondary" style={{ marginLeft: 'auto' }}>
                    {filteredDocs.length} / {docs.length} {__('documenti', 'gepafin')}
                </small>
            )}
        </div>
    );

    return (
        <Dialog header={dialogHeader} visible={visible} onHide={onHide}
                style={{ width: '1000px', maxWidth: '95vw' }}
                modal dismissableMask footer={footer}
                contentStyle={{ paddingTop: '1rem' }}>

            <Message severity="info" style={{ width: '100%', marginBottom: '1.5rem' }}
                content={
                    <small>{__('Seleziona un documento gia caricato. Se esistono piu versioni per la stessa categoria, viene mostrata solo la piu recente valida. I documenti scaduti sono esclusi.', 'gepafin')}</small>
                } />

            {/* tab origine — 3 pulsanti manuali (SelectButton di PrimeReact ha issues di styling col tema Gepafin) */}
            <div style={{ display: 'flex', gap: '0.5rem', marginBottom: '1rem', flexWrap: 'wrap' }}>
                <Button type="button" size="small"
                    label={__('Tutti', 'gepafin')}
                    outlined={originFilter !== 'ALL'}
                    onClick={() => setOriginFilter('ALL')}
                    style={{ flex: 1 }} />
                <Button type="button" size="small" icon="pi pi-building"
                    label={__('Azienda', 'gepafin')}
                    outlined={originFilter !== 'COMPANY_DOCUMENT'}
                    onClick={() => setOriginFilter('COMPANY_DOCUMENT')}
                    style={{ flex: 1 }} />
                <Button type="button" size="small" icon="pi pi-user"
                    label={__('Amministratore', 'gepafin')}
                    outlined={originFilter !== 'PERSONAL_DOCUMENT'}
                    onClick={() => setOriginFilter('PERSONAL_DOCUMENT')}
                    style={{ flex: 1 }} />
            </div>

            {/* filtri secondari */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '0.75rem', marginBottom: '1rem' }}>
                <div style={{ position: 'relative', width: '100%' }}>
                    <i className="pi pi-search" style={{ position: 'absolute', left: '1rem', top: '50%',
                        transform: 'translateY(-50%)', color: 'var(--text-color-secondary)',
                        pointerEvents: 'none', zIndex: 1 }} />
                    <InputText placeholder={__('Cerca per nome o categoria...', 'gepafin')}
                        value={search} onChange={(e) => setSearch(e.target.value)}
                        style={{ width: '100%', paddingLeft: '2.75rem' }} />
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.75rem' }}>
                    <Dropdown value={categoryFilter} onChange={(e) => setCategoryFilter(e.value)}
                        options={categoryOptions} placeholder={__('Categoria', 'gepafin')}
                        showClear style={{ width: '100%' }} />
                    <Dropdown value={statusFilter} onChange={(e) => setStatusFilter(e.value)}
                        options={statusOptions} placeholder={__('Stato', 'gepafin')}
                        showClear style={{ width: '100%' }} />
                </div>
            </div>

            {loading ? (
                <div><Skeleton height="2.5rem" className="mb-2" /><Skeleton height="2.5rem" className="mb-2" /><Skeleton height="2.5rem" /></div>
            ) : error ? (
                <Message severity="error" text={error} style={{ width: '100%' }} />
            ) : (
                <DataTable value={filteredDocs} dataKey="id"
                    emptyMessage={<div style={{ textAlign: 'center', padding: '2rem', color: 'var(--text-color-secondary)' }}>
                        <i className="pi pi-inbox" style={{ fontSize: '2rem', display: 'block', marginBottom: '0.5rem' }} />
                        {docs.length === 0
                            ? __('Nessun documento nel repository della tua azienda', 'gepafin')
                            : __('Nessun documento corrisponde ai filtri', 'gepafin')}
                    </div>}
                    size="small" stripedRows
                    paginator rows={10}
                    paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport"
                    currentPageReportTemplate="{first}-{last} di {totalRecords}"
                    selectionMode="single" selection={chosenDoc}
                    onSelectionChange={(e) => e.value && setSelectedId(e.value.id)}
                    rowClassName={(row) => row.id === selectedId ? 'p-highlight' : ''}
                    style={{ cursor: 'pointer' }}>
                    <Column header={__('Documento', 'gepafin')} body={nameTpl} style={{ minWidth: '240px' }} />
                    <Column header={__('Origine', 'gepafin')} body={originTpl} style={{ width: '150px' }} />
                    <Column header={__('Categoria', 'gepafin')} body={categoryTpl} style={{ width: '170px' }} />
                    <Column header={__('Stato', 'gepafin')} body={statusTpl} style={{ width: '160px' }} />
                    <Column header={__('Scadenza', 'gepafin')} body={expiryTpl} style={{ width: '110px' }} />
                </DataTable>
            )}
        </Dialog>
    );
};

export default CompanyDocumentPicker;
