// Archive View Component
const { useState, useEffect } = React;

const ArchiveView = () => {
    const toast = useToast();
    const [jobs, setJobs] = useState([]);
    const [loading, setLoading] = useState(true);
    const [confirmDelete, setConfirmDelete] = useState(null); // jobId

    useEffect(() => {
        fetch('/queue/archived').then(r => r.json()).then(data => {
            if (data.status === 'success') setJobs(data.jobs || []);
        }).catch(console.error).finally(() => setLoading(false));
    }, []);

    const handleDelete = (id) => {
        setConfirmDelete(id);
    };

    const executeDelete = async () => {
        if (!confirmDelete) return;

        try {
            const r = await fetch(`/queue/job/${confirmDelete}/permanent`, { method: 'DELETE' });
            if (r.ok) {
                toast('Lavoro eliminato', 'success');
                setJobs(j => j.filter(x => x.id !== confirmDelete));
            }
            setConfirmDelete(null);
        } catch (e) {
            toast('Errore eliminazione', 'error');
            setConfirmDelete(null);
        }
    };

    const handleRestore = async (id) => {
        try {
            const r = await fetch(`/queue/job/${id}/restore`, { method: 'POST' });
            if (r.ok) {
                toast('Lavoro ripristinato in coda', 'success');
                setJobs(j => j.filter(x => x.id !== id));
            } else {
                const data = await r.json();
                toast(data.detail || 'Errore ripristino', 'error');
            }
        } catch (e) { toast('Errore ripristino', 'error'); }
    };

    const getStatusInfo = (job) => {
        const isSuccess = job.result?.status === 'success';
        const isCancelled = job.status === 'cancelled' || job.result?.status === 'cancelled';

        if (isCancelled) {
            return {
                color: 'bg-orange-500',
                bgLight: 'bg-orange-100',
                textColor: 'text-orange-700',
                label: 'Annullato',
                percent: 0
            };
        }
        if (isSuccess) {
            return {
                color: 'bg-green-500',
                bgLight: 'bg-green-100',
                textColor: 'text-green-700',
                label: 'Completato',
                percent: 100
            };
        }
        return {
            color: 'bg-red-500',
            bgLight: 'bg-red-100',
            textColor: 'text-red-700',
            label: 'Fallito',
            percent: 0
        };
    };

    const formatDate = (dateString) => {
        if (!dateString) return '-';
        return new Date(dateString).toLocaleDateString('it-IT', {
            day: '2-digit',
            month: 'short',
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    return (
        <div className="p-6 space-y-6">
            {/* Header */}
            <div>
                <h2 className="text-2xl font-bold text-slate-800">Archivio</h2>
                <p className="text-slate-500 mt-1">Cronologia dei lavori archiviati</p>
            </div>

            {loading ? (
                <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-12 text-center">
                    <Spinner size="lg" />
                    <p className="text-slate-500 mt-4">Caricamento archivio...</p>
                </div>
            ) : jobs.length === 0 ? (
                <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-12 text-center">
                    <svg className="w-16 h-16 text-slate-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4" />
                    </svg>
                    <p className="text-slate-600 font-medium">Archivio vuoto</p>
                    <p className="text-slate-400 text-sm mt-1">I lavori archiviati appariranno qui</p>
                </div>
            ) : (
                <div className="grid gap-3 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5">
                    {jobs.map(job => {
                        const statusInfo = getStatusInfo(job);
                        const isSuccess = job.result?.status === 'success';
                        const isCancelled = job.status === 'cancelled' || job.result?.status === 'cancelled';
                        const fullName = `${job.personal_data?.first_name || ''} ${job.personal_data?.last_name || ''}`.trim();
                        const initials = fullName ? fullName.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase() : '?';

                        return (
                            <div
                                key={job.id}
                                className={`bg-white rounded-lg shadow-sm border overflow-hidden hover:shadow-md transition-shadow ${
                                    isCancelled
                                        ? 'border-orange-200'
                                        : isSuccess
                                            ? 'border-slate-200'
                                            : 'border-red-200'
                                }`}
                            >
                                {/* Colored Top Border */}
                                <div className={`h-1 ${statusInfo.color}`} />

                                <div className="p-3">
                                    {/* Row 1: Name & Status Badge */}
                                    <div className="flex items-center justify-between gap-2 mb-2">
                                        <h3 className="font-semibold text-sm text-slate-800 truncate flex-1">
                                            {fullName || 'N/A'}
                                        </h3>
                                        <span className={`px-2 py-0.5 text-[10px] font-medium rounded-full flex-shrink-0 ${statusInfo.bgLight} ${statusInfo.textColor}`}>
                                            {statusInfo.label}
                                        </span>
                                    </div>

                                    {/* Row 2: Progress Badge & Date */}
                                    <div className="flex items-center justify-between mb-2">
                                        <span className={`px-2 py-0.5 text-[10px] font-medium rounded-full ${
                                            isSuccess
                                                ? 'bg-green-100 text-green-700'
                                                : isCancelled
                                                    ? 'bg-orange-100 text-orange-700'
                                                    : 'bg-red-100 text-red-700'
                                        }`}>
                                            {statusInfo.percent}%
                                        </span>
                                        <span className="flex items-center gap-1 text-[11px] text-slate-500">
                                            <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                                            </svg>
                                            {formatDate(job.archived_at || job.updated_at)}
                                        </span>
                                    </div>

                                    {/* Row 3: Avatar & Actions */}
                                    <div className="flex items-center justify-between pt-2 border-t border-slate-100">
                                        {/* User Avatar */}
                                        <div
                                            className={`w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-medium ${
                                                isSuccess
                                                    ? 'bg-green-100 text-green-700'
                                                    : isCancelled
                                                        ? 'bg-orange-100 text-orange-700'
                                                        : 'bg-red-100 text-red-700'
                                            }`}
                                            title={fullName || 'N/A'}
                                        >
                                            {initials}
                                        </div>

                                        {/* Action Buttons */}
                                        <div className="flex items-center gap-0.5">
                                            <button
                                                onClick={() => handleRestore(job.id)}
                                                className="p-1 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors"
                                                title="Ripristina in coda"
                                            >
                                                <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6" />
                                                </svg>
                                            </button>
                                            <button
                                                onClick={() => handleDelete(job.id)}
                                                className="p-1 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
                                                title="Elimina definitivamente"
                                            >
                                                <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                                </svg>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        );
                    })}
                </div>
            )}

            {/* Confirmation Modal */}
            {confirmDelete && (
                <ConfirmationModal
                    title="Elimina Definitivamente"
                    message="Sei sicuro di voler eliminare definitivamente questo lavoro? Questa azione non può essere annullata."
                    confirmText="Elimina"
                    variant="danger"
                    onConfirm={executeDelete}
                    onCancel={() => setConfirmDelete(null)}
                />
            )}
        </div>
    );
};

window.ArchiveView = ArchiveView;
