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

import { Button } from 'primereact/button';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Tag } from 'primereact/tag';
import { Toast } from 'primereact/toast';
import { Skeleton } from 'primereact/skeleton';
import { Dialog } from 'primereact/dialog';
import { Dropdown } from 'primereact/dropdown';
import { InputTextarea } from 'primereact/inputtextarea';

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

const STATUS_TAGS = {
    SUBMITTED: { severity: 'info', label: 'Da prendere in carico' },
    UNDER_REVIEW: { severity: 'warning', label: 'In valutazione' },
    AWAITING_AMENDMENT: { severity: 'warning', label: 'Soccorso istruttorio' }
};

const euro = (v) => '€ ' + Number(v || 0).toLocaleString('it-IT', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const formatDate = (d) => d ? new Date(d).toLocaleDateString('it-IT') : '—';

const IstruttoriaQueue = () => {
    const navigate = useNavigate();
    const toast = useRef(null);
    const [items, setItems] = useState([]);
    const [isManagerFromQueue, setIsManagerFromQueue] = useState(false);
    const [loading, setLoading] = useState(true);

    // v2 manager view
    // Default: manager/superadmin partono in vista 'tutte le pratiche' (managerMode=true).
    // Pre-instructor vedono solo la coda attiva (managerMode=false).
    const [managerMode, setManagerMode] = useState(
        storeGet('getRole') === 'ROLE_INSTRUCTOR_MANAGER' ||
        storeGet('getRole') === 'ROLE_SUPER_ADMIN'
    );  // toggle UI
    const [managerItems, setManagerItems] = useState([]);
    const [instructors, setInstructors] = useState([]);
    const [reassignDialog, setReassignDialog] = useState({ visible: false, practice: null, newInstructorId: null, reason: '' });
    const [reassigning, setReassigning] = useState(false);

    // Controllo ruolo utente per mostrare toggle manager.
    // storeGet('getRole') ritorna userData.role.roleType (es. ROLE_INSTRUCTOR_MANAGER).
    // Fix: il codice precedente usava storeGet('getUser') che non esiste nel selectors,
    // quindi canUseManagerView era sempre false e il toggle non compariva mai.
    const userRole = storeGet('getRole');
    const canUseManagerView = userRole === 'ROLE_INSTRUCTOR_MANAGER' || userRole === 'ROLE_SUPER_ADMIN';

    const loadQueue = () => {
        setLoading(true);
        RendicontazioneService.instructorQueue(
            (resp) => {
                setItems(resp?.data?.items || []);
                setIsManagerFromQueue(!!resp?.data?.manager_view);
                setLoading(false);
            },
            (err) => {
                toast.current?.show({ severity: 'error', summary: __('Errore', 'gepafin'), detail: err?.detail });
                setLoading(false);
            }
        );
    };

    const loadManagerAssignments = () => {
        setLoading(true);
        RendicontazioneService.managerAssignments(
            (resp) => {
                setManagerItems(resp?.data?.assignments || []);
                setLoading(false);
            },
            (err) => {
                toast.current?.show({ severity: 'error', summary: __('Errore', 'gepafin'), detail: err?.detail });
                setLoading(false);
            }
        );
    };

    const loadInstructors = () => {
        RendicontazioneService.managerInstructorsList(
            (resp) => setInstructors(resp?.data?.instructors || []),
            () => {}
        );
    };

    useEffect(() => {
        if (managerMode) {
            loadManagerAssignments();
            if (instructors.length === 0) loadInstructors();
        } else {
            loadQueue();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [managerMode]);

    const openReassign = (row) => {
        if (instructors.length === 0) loadInstructors();
        setReassignDialog({
            visible: true,
            practice: row,
            newInstructorId: row.assigned_instructor_id || null,
            reason: ''
        });
    };

    const confirmReassign = () => {
        const { practice, newInstructorId, reason } = reassignDialog;
        setReassigning(true);
        RendicontazioneService.reassignInstructor(
            practice.id, newInstructorId, reason,
            (resp) => {
                setReassigning(false);
                setReassignDialog({ visible: false, practice: null, newInstructorId: null, reason: '' });
                toast.current?.show({ severity: 'success', summary: resp?.message || __('Pratica riassegnata', 'gepafin') });
                loadManagerAssignments();
            },
            (err) => {
                setReassigning(false);
                toast.current?.show({ severity: 'error', summary: __('Riassegnazione fallita', 'gepafin'), detail: err?.detail });
            }
        );
    };

    // ---------- templates ----------
    const callTpl = (row) => (
        <div>
            <strong>{row.call_name || `Bando #${row.call_id}`}</strong>
            <div><small className="text-color-secondary">{row.company_name} · pratica #{row.application_id}</small></div>
        </div>
    );
    const statusTpl = (row) => {
        const c = STATUS_TAGS[row.status] || { severity: 'secondary', label: row.status };
        return <div>
            <Tag value={c.label} severity={c.severity} />
            {row.open_amendments > 0 && (
                <div style={{ marginTop: '4px' }}>
                    <Tag value={`${row.open_amendments} soccorso aperto`} severity="warning" icon="pi pi-clock" />
                </div>
            )}
        </div>;
    };
    const submittedTpl = (row) => row.submitted_at ? formatDate(row.submitted_at) : '—';
    const erogatoTpl = (row) => <strong>{euro(row.amount_erogato)}</strong>;
    const remissionTpl = (row) => row.remission_due != null
        ? <span style={{ color: 'var(--primary-color)', fontWeight: 600 }}>{euro(row.remission_due)}</span>
        : <span className="text-color-secondary">—</span>;
    const progressTpl = (row) => (
        <small className="text-color-secondary">
            {row.invoice_count} {__('fatt.', 'gepafin')} · {row.ula_count} {__('dip.', 'gepafin')} · {row.document_count} {__('doc', 'gepafin')}
        </small>
    );
    const actionsTpl = (row) => {
        const label = row.status === 'SUBMITTED' ? __('Apri e prendi in carico', 'gepafin') : __('Apri', 'gepafin');
        return <Button icon="pi pi-eye" label={label} size="small"
            outlined={row.status !== 'SUBMITTED'}
            onClick={() => navigate(`/istruttoria/${row.id}`)} />;
    };
    const assignedTpl = (row) => {
        if (!row.assigned_instructor_id) return <span className="text-color-secondary">—</span>;
        return <span>#{row.assigned_instructor_id}</span>;
    };

    // Manager view templates
    const mgrCallTpl = (row) => (
        <div>
            <strong>{row.call_name || `Bando #${row.call_id}`}</strong>
            <div><small className="text-color-secondary">{row.company_name} · pratica #{row.application_id} · <strong>T{row.sequence_number}</strong>{row.period_label ? ` — ${row.period_label}` : ''}</small></div>
        </div>
    );
    const mgrSuggestedTpl = (row) => (
        row.suggested_instructor_id
            ? <div><strong>{row.suggested_instructor_name || `#${row.suggested_instructor_id}`}</strong></div>
            : <span className="text-color-secondary">{__('nessuno', 'gepafin')}</span>
    );
    const mgrAssignedTpl = (row) => {
        if (row.is_unassigned) {
            return <Tag severity="warning" value={__('Da assegnare', 'gepafin')} icon="pi pi-exclamation-triangle" />;
        }
        return <div><strong>{row.assigned_instructor_name || `#${row.assigned_instructor_id}`}</strong></div>;
    };
    const mgrActionsTpl = (row) => (
        <div style={{ display: 'flex', gap: '0.4rem' }}>
            <Button icon="pi pi-eye" size="small" outlined
                label={__('Apri', 'gepafin')}
                onClick={() => navigate(`/istruttoria/${row.id}`)} />
            <Button icon="pi pi-user-edit" size="small" severity="warning"
                label={row.is_unassigned ? __('Assegna', 'gepafin') : __('Riassegna', 'gepafin')}
                onClick={() => openReassign(row)} />
        </div>
    );

    return (
        <div className="appPage">
            <Toast ref={toast} />

            <div className="appPage__pageHeader">
                <h1>{__('Coda istruttoria', 'gepafin')}</h1>
                <p>
                    {managerMode
                        ? __('Vista manager: tutte le pratiche inviate con istruttore suggerito e assegnato. Puoi riassegnare le pratiche da qui.', 'gepafin')
                        : (isManagerFromQueue
                            ? __('Vista manager: vedi tutte le pratiche in carico a tutti gli istruttori.', 'gepafin')
                            : __('Pool di pratiche da prendere in carico + pratiche assegnate a te.', 'gepafin'))}
                </p>
            </div>

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

            {/* TOGGLE MANAGER VIEW */}
            {canUseManagerView && (
                <div className="appPageSection">
                    <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
                        <Button icon="pi pi-list"
                            label={__('Coda standard', 'gepafin')}
                            outlined={managerMode}
                            severity={managerMode ? 'secondary' : 'info'}
                            onClick={() => setManagerMode(false)} />
                        <Button icon="pi pi-users"
                            label={__('Vista manager (riassegnazioni)', 'gepafin')}
                            outlined={!managerMode}
                            severity={!managerMode ? 'secondary' : 'warning'}
                            onClick={() => setManagerMode(true)} />
                    </div>
                </div>
            )}

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

            {/* CODA STANDARD */}
            {!managerMode && (
                <div className="appPageSection">
                    {loading && <Skeleton width="100%" height="10rem" />}
                    {!loading && items.length === 0 && (
                        <div style={{ padding: '2rem', textAlign: 'center', width: '100%' }}>
                            <i className="pi pi-inbox" style={{ fontSize: '2.5rem', color: 'var(--text-color-secondary)', display: 'block', marginBottom: '0.75rem' }} />
                            <p>{__('Nessuna pratica in coda al momento.', 'gepafin')}</p>
                        </div>
                    )}
                    {!loading && items.length > 0 && (
                        <DataTable value={items} dataKey="id" stripedRows responsiveLayout="scroll" style={{ width: '100%' }}>
                            <Column header={__('Bando / Azienda', 'gepafin')} body={callTpl} />
                            <Column header={__('Inviata il', 'gepafin')} body={submittedTpl} style={{ width: '140px' }} />
                            <Column header={__('Stato', 'gepafin')} body={statusTpl} style={{ width: '180px' }} />
                            <Column header={__('Istruttore', 'gepafin')} body={assignedTpl} style={{ width: '100px' }} />
                            <Column header={__('Erogato', 'gepafin')} body={erogatoTpl} style={{ width: '130px' }} />
                            <Column header={__('Remissione', 'gepafin')} body={remissionTpl} style={{ width: '140px' }} />
                            <Column header={__('Contenuto', 'gepafin')} body={progressTpl} />
                            <Column header={__('Azione', 'gepafin')} body={actionsTpl} style={{ width: '220px' }} />
                        </DataTable>
                    )}
                </div>
            )}

            {/* VISTA MANAGER */}
            {managerMode && (
                <div className="appPageSection">
                    {loading && <Skeleton width="100%" height="10rem" />}
                    {!loading && managerItems.length === 0 && (
                        <div style={{ padding: '2rem', textAlign: 'center', width: '100%' }}>
                            <i className="pi pi-check-circle" style={{ fontSize: '2.5rem', color: 'var(--green-500)', display: 'block', marginBottom: '0.75rem' }} />
                            <p>{__('Nessuna pratica attiva da gestire.', 'gepafin')}</p>
                        </div>
                    )}
                    {!loading && managerItems.length > 0 && (
                        <DataTable value={managerItems} dataKey="id" stripedRows responsiveLayout="scroll" style={{ width: '100%' }}>
                            <Column header={__('Bando / Pratica / Tranche', 'gepafin')} body={mgrCallTpl} />
                            <Column header={__('Inviata il', 'gepafin')} body={submittedTpl} style={{ width: '140px' }} />
                            <Column header={__('Stato', 'gepafin')} body={statusTpl} style={{ width: '170px' }} />
                            <Column header={__('Istruttore domanda', 'gepafin')} body={mgrSuggestedTpl} style={{ width: '180px' }} />
                            <Column header={__('Assegnato a', 'gepafin')} body={mgrAssignedTpl} style={{ width: '200px' }} />
                            <Column header={__('Erogato', 'gepafin')} body={erogatoTpl} style={{ width: '120px' }} />
                            <Column header={__('Azioni', 'gepafin')} body={mgrActionsTpl} style={{ width: '260px' }} />
                        </DataTable>
                    )}
                </div>
            )}

            {/* DIALOG RIASSEGNA */}
            <Dialog header={__('Riassegna pratica', 'gepafin')}
                visible={reassignDialog.visible} style={{ width: '520px' }}
                onHide={() => !reassigning && setReassignDialog({ visible: false, practice: null, newInstructorId: null, reason: '' })}
                modal
                footer={(
                    <div>
                        <Button label={__('Annulla', 'gepafin')} icon="pi pi-times"
                            onClick={() => setReassignDialog({ visible: false, practice: null, newInstructorId: null, reason: '' })}
                            outlined disabled={reassigning} />
                        <Button label={__('Conferma', 'gepafin')} icon="pi pi-check" iconPos="right"
                            severity="warning" loading={reassigning} onClick={confirmReassign} />
                    </div>
                )}>
                {reassignDialog.practice && (
                    <div>
                        <p style={{ marginTop: 0 }}>
                            <strong>{reassignDialog.practice.call_name}</strong> — pratica #{reassignDialog.practice.application_id}
                            {' '}T{reassignDialog.practice.sequence_number}
                            {reassignDialog.practice.period_label && ` — ${reassignDialog.practice.period_label}`}
                        </p>
                        <p style={{ color: 'var(--text-color-secondary)' }}>
                            {__('Istruttore domanda', 'gepafin')}: <strong>{reassignDialog.practice.suggested_instructor_name || __('nessuno', 'gepafin')}</strong>
                            <br />
                            {__('Attualmente assegnato a', 'gepafin')}: <strong>{reassignDialog.practice.assigned_instructor_name || __('nessuno', 'gepafin')}</strong>
                        </p>
                        <div className="appForm__field">
                            <label>{__('Nuovo istruttore', 'gepafin')}</label>
                            <Dropdown value={reassignDialog.newInstructorId}
                                options={[
                                    { user_id: null, display_name: __('— Metti in coda (nessuno) —', 'gepafin') },
                                    ...instructors
                                ]}
                                optionLabel="display_name" optionValue="user_id"
                                onChange={(e) => setReassignDialog(d => ({ ...d, newInstructorId: e.value }))}
                                disabled={reassigning}
                                placeholder={__('Seleziona istruttore', 'gepafin')} />
                            <small className="text-color-secondary">
                                {__('Se la pratica era in SUBMITTED e assegni a qualcuno, passa automaticamente a IN LAVORAZIONE.', 'gepafin')}
                            </small>
                        </div>
                        <div className="appForm__field" style={{ marginTop: '1rem' }}>
                            <label>{__('Motivazione (opzionale, audit log)', 'gepafin')}</label>
                            <InputTextarea value={reassignDialog.reason} rows={3} autoResize
                                onChange={(e) => setReassignDialog(d => ({ ...d, reason: e.target.value }))}
                                placeholder={__('Es: carico di lavoro, competenza specifica, assenza istruttore...', 'gepafin')}
                                disabled={reassigning} />
                        </div>
                    </div>
                )}
            </Dialog>
        </div>
    );
};

export default IstruttoriaQueue;
