import React, { useEffect, useState } from 'react'; import { fetchNotificaciones, fetchAllNotifications, marcarNotificacionComoVista } from '../api/notificaciones'; // Función para obtener el icono apropiado según el tipo de notificación const getNotificationIcon = (tipo) => { const iconProps = "w-6 h-6"; switch (tipo) { case 'success': case 'exito': return (
); case 'error': case 'danger': return (
); case 'warning': case 'advertencia': return (
); case 'info': case 'informacion': return (
); case 'documento': case 'document': return (
); case 'proceso': case 'process': return (
); default: return (
); } }; // Función para formatear timestamps const formatTimestamp = (timestamp) => { if (!timestamp) return 'Fecha no disponible'; try { const date = new Date(timestamp); const now = new Date(); const diffInMinutes = Math.floor((now - date) / (1000 * 60)); const diffInHours = Math.floor(diffInMinutes / 60); const diffInDays = Math.floor(diffInHours / 24); if (diffInMinutes < 1) { return 'Ahora mismo'; } else if (diffInMinutes < 60) { return `Hace ${diffInMinutes} min`; } else if (diffInHours < 24) { return `Hace ${diffInHours} h`; } else if (diffInDays < 7) { return `Hace ${diffInDays} días`; } else { return date.toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }); } } catch (error) { return 'Fecha inválida'; } }; export default function Notificaciones() { const [notificaciones, setNotificaciones] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [page, setPage] = useState(1); const pageSize = 15; const [count, setCount] = useState(0); const [filtroVisto, setFiltroVisto] = useState('todos'); const fetchData = async () => { setLoading(true); setError(null); try { let data; if (filtroVisto === 'todos') { data = await fetchAllNotifications({ page, pageSize }); } else { const params = { page, pageSize }; if (filtroVisto === 'visto') params.visto = true; else if (filtroVisto === 'novisto') params.visto = false; data = await fetchNotificaciones(params); } setNotificaciones(data.results); setCount(data.count); } catch (e) { setError('Error al cargar notificaciones'); } finally { setLoading(false); } }; useEffect(() => { fetchData(); // eslint-disable-next-line }, [page, filtroVisto]); const handleActualizarTodas = async () => { setLoading(true); try { await Promise.all( notificaciones.filter(n => !n.visto).map(n => marcarNotificacionComoVista(n.id)) ); fetchData(); } catch (e) { setError('Error al actualizar notificaciones'); } finally { setLoading(false); } }; const handleFiltroChange = (e) => { setFiltroVisto(e.target.value); setPage(1); }; return (
{/* Header moderno */}

Notificaciones

{count > 0 ? `${count} notificaciones encontradas` : 'No hay notificaciones'}

{/* Filtro mejorado */}
{/* Botón de acción mejorado */}
{/* Contenido principal */} {loading ? (
Cargando notificaciones...
) : error ? (
{error}
) : ( <> {/* Vista Desktop - Tabla */}
{notificaciones.map((n, idx) => ( ))} {/* Filas vacías para mantener altura consistente */} {Array.from({ length: Math.max(0, pageSize - notificaciones.length) }).map((_, idx) => ( ))}
ID Tipo Mensaje Fecha Estado
#{n.id}
{getNotificationIcon(n.tipo?.tipo)} {n.tipo?.descripcion || n.tipo?.tipo || 'Notificación'}
{n.mensaje} {formatTimestamp(n.fecha_envio || n.created_at)} {n.visto ? ( Leída ) : ( Nueva )}
-
{/* Vista Mobile - Cards */}
{notificaciones.length === 0 ? (

No hay notificaciones

No se encontraron notificaciones con los filtros aplicados.

) : ( notificaciones.map((n, idx) => (
{getNotificationIcon(n.tipo?.tipo)}

{n.tipo?.descripcion || n.tipo?.tipo || 'Notificación'}

{n.visto ? ( Leída ) : ( Nueva )}

{n.mensaje}

ID: #{n.id} {formatTimestamp(n.fecha_envio || n.created_at)}
)) )}
)} {/* Paginación mejorada */} {!loading && !error && count > 0 && (
Página {page} de {Math.ceil(count / pageSize) || 1} • {count} notificaciones totales
15 por página
)}
); }