'use client' import { useState, useCallback, useEffect } from 'react' import { Button } from '@nextsparkjs/core/components/ui/button' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@nextsparkjs/core/components/ui/card' import { Badge } from '@nextsparkjs/core/components/ui/badge' import { Switch } from '@nextsparkjs/core/components/ui/switch' import { Alert, AlertDescription } from '@nextsparkjs/core/components/ui/alert' import { toast } from 'sonner' import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from '@nextsparkjs/core/components/ui/dialog' import { Shield, Smartphone, Monitor, Globe, AlertTriangle, Check, X, Eye, Clock, MapPin, Wifi, Save, Loader2 } from 'lucide-react' import { useTranslations } from 'next-intl' import { useUserWithMetaSettings } from '@nextsparkjs/core/hooks/useUserSettings' import { SecurityPageSkeleton } from '@nextsparkjs/core/components/settings/SettingsPageSkeleton' import { getTemplateOrDefaultClient } from '@nextsparkjs/registries/template-registry.client' function SecurityPage() { const t = useTranslations('settings') // Hook para manejar user metadata con autenticación de sesión const { data: userData, isLoading: isLoadingUser, updateEntity: updateUserMeta, isUpdating } = useUserWithMetaSettings() const [twoFactorEnabled, setTwoFactorEnabled] = useState(false) const [loginAlertsEnabled, setLoginAlertsEnabled] = useState(true) const [statusMessage, setStatusMessage] = useState('') const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false) // Cargar configuraciones desde metadata al montar el componente useEffect(() => { if (userData?.meta?.securityPreferences) { const securityPrefs = userData.meta.securityPreferences as Record if (securityPrefs.twoFactorEnabled !== undefined) { setTwoFactorEnabled(securityPrefs.twoFactorEnabled as boolean) } if (securityPrefs.loginAlertsEnabled !== undefined) { setLoginAlertsEnabled(securityPrefs.loginAlertsEnabled as boolean) } setHasUnsavedChanges(false) } }, [userData?.meta]) // Datos de ejemplo para sesiones activas const activeSessions = [ { id: '1', device: 'MacBook Pro', browser: 'Chrome 120', location: 'Buenos Aires, Argentina', ip: '192.168.1.100', lastActive: '2 minutos atrás', current: true, icon: }, { id: '2', device: 'iPhone 15 Pro', browser: 'Safari Mobile', location: 'Buenos Aires, Argentina', ip: '192.168.1.101', lastActive: '1 hora atrás', current: false, icon: }, { id: '3', device: 'Unknown Device', browser: 'Chrome 119', location: 'Córdoba, Argentina', ip: '200.45.123.45', lastActive: '3 días atrás', current: false, icon: } ] // Datos de ejemplo para historial de logins const loginHistory = [ { id: '1', success: true, location: 'Buenos Aires, Argentina', device: 'MacBook Pro - Chrome', timestamp: '2024-01-15 10:30:00', ip: '192.168.1.100' }, { id: '2', success: true, location: 'Buenos Aires, Argentina', device: 'iPhone 15 Pro - Safari', timestamp: '2024-01-15 08:45:00', ip: '192.168.1.101' }, { id: '3', success: false, location: 'Madrid, España', device: 'Unknown - Chrome', timestamp: '2024-01-14 22:15:00', ip: '85.123.45.67' }, { id: '4', success: true, location: 'Buenos Aires, Argentina', device: 'MacBook Pro - Chrome', timestamp: '2024-01-14 09:20:00', ip: '192.168.1.100' } ] const handleTerminateSession = useCallback((sessionId: string) => { console.log('Terminating session:', sessionId) setStatusMessage(t('security.messages.sessionTerminated')) // Aquí iría la lógica para terminar la sesión }, [t]) const handleTwoFactorToggle = useCallback((enabled: boolean) => { setTwoFactorEnabled(enabled) setStatusMessage(enabled ? t('security.messages.twoFactorEnabled') : t('security.messages.twoFactorDisabled')) setHasUnsavedChanges(true) }, [t]) const handleLoginAlertsToggle = useCallback((enabled: boolean) => { setLoginAlertsEnabled(enabled) setStatusMessage(enabled ? t('security.messages.alertsEnabled') : t('security.messages.alertsDisabled')) setHasUnsavedChanges(true) }, [t]) // Función para guardar configuraciones como metadata const handleSaveSettings = useCallback(async () => { try { // Crear metadata en formato anidado const securityPreferences = { twoFactorEnabled: twoFactorEnabled, loginAlertsEnabled: loginAlertsEnabled, } await updateUserMeta({ meta: { securityPreferences } }) setHasUnsavedChanges(false) toast.success(t('security.messages.saveSuccess'), { description: t('security.messages.saveSuccessDescription'), }) } catch (error) { console.error('Error saving security settings:', error) toast.error(t('security.messages.saveError'), { description: t('security.messages.saveErrorDescription'), }) } }, [twoFactorEnabled, loginAlertsEnabled, updateUserMeta, t]) // Mostrar skeleton mientras cargan los datos if (isLoadingUser) { return } return ( <> {/* MANDATORY: Screen reader announcements */}
{statusMessage}
{/* Header */}

{t('security.title')}

{t('security.description')}

{/* Main Security Settings Card */} {t('security.main.title')} {t('security.main.description')} {/* Autenticación de Dos Factores */}

{t('security.twoFactor.title')}

{twoFactorEnabled ? t('security.twoFactor.enabled') : t('security.twoFactor.disabled')}

{twoFactorEnabled ? t('security.twoFactor.enabledStatus') : t('security.twoFactor.disabledStatus') }

{twoFactorEnabled ? t('security.twoFactor.active') : t('security.twoFactor.inactive')}
{!twoFactorEnabled && ( {t('security.twoFactor.recommendation')} )} {twoFactorEnabled && (

{t('security.twoFactor.configuredMethods')}

{t('security.twoFactor.appAuthenticator')}

{t('security.twoFactor.appDescription')}

{t('security.twoFactor.configured')}
)}
{/* Divisor */}
{/* Alertas de Seguridad */}

{t('security.alerts.title')}

{t('security.alerts.loginTitle')}

{t('security.alerts.loginDescription')}

{/* Botón de Guardar */}
{/* Two Column Layout for Sessions and History */}
{/* Sesiones Activas */} {t('security.sessions.title')} {t('security.sessions.description')}
{activeSessions.map((session) => (
{/* Header Row */}
{session.icon}

{session.device}

{session.current && ( {t('security.sessions.current')} )}

{session.browser}

{!session.current && (
{t('security.sessions.terminateDialog.title')} {t('security.sessions.terminateDialog.description')}
)}
{/* Details Row */}
{session.location} {session.ip} {session.lastActive}
))}
{/* Historial de Accesos */} {t('security.loginHistory.title')} {t('security.loginHistory.description')}
{loginHistory.map((login) => (
{/* Header Row */}
{login.success ? ( ) : ( )}

{login.success ? t('security.loginHistory.successful') : t('security.loginHistory.failed')}

{login.success ? t('security.loginHistory.successBadge') : t('security.loginHistory.failBadge')}
{/* Details Row */}
{login.location} {login.device} {new Date(login.timestamp).toLocaleString()}
))}
) } export default getTemplateOrDefaultClient('app/dashboard/settings/security/page.tsx', SecurityPage)