'use client'; import React, { useState, useCallback } from 'react'; import { CalendarConnection } from '@/lib/calendar-sync'; interface CalendarSettingsProps { connections: CalendarConnection[]; onConnectionAdded?: (connection: CalendarConnection) => void; onConnectionRemoved?: (connectionId: string) => void; onSyncTriggered?: (connectionId: string) => void; } const CalendarSettings: React.FC = ({ connections, onConnectionAdded, onConnectionRemoved, onSyncTriggered }) => { const [isSyncing, setIsSyncing] = useState>({}); const [lastSyncTime, setLastSyncTime] = useState>({}); const [showConfirmation, setShowConfirmation] = useState(null); // Apple Calendar State const [showAppleModal, setShowAppleModal] = useState(false); const [appleEmail, setAppleEmail] = useState(''); const [applePassword, setApplePassword] = useState(''); const [isConnectingApple, setIsConnectingApple] = useState(false); const [appleError, setAppleError] = useState(''); const [needs2FA, setNeeds2FA] = useState(false); const [securityCode, setSecurityCode] = useState(''); // Memoized functions for performance const formatDate = useCallback((date?: Date) => { if (!date) return 'Never'; return date.toLocaleString(); }, []); // Function to trigger Google OAuth const handleGoogleConnect = useCallback(() => { // In a real implementation, this would redirect to Google OAuth flow // For now, we'll just log the action console.log('Redirecting to Google OAuth flow...'); // window.location.href = '/api/calendar/google/oauth'; }, []); // Function to trigger Apple Connect Modal const handleAppleConnect = useCallback(() => { setShowAppleModal(true); setAppleError(''); setAppleEmail(''); setApplePassword(''); setNeeds2FA(false); setSecurityCode(''); }, []); const submitAppleConnection = async () => { if (!appleEmail || !applePassword) { setAppleError('Please enter both email and password.'); return; } setIsConnectingApple(true); setAppleError(''); try { const response = await fetch('/api/reminders/connect', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: appleEmail, password: applePassword }), }); const data = await response.json(); if (!response.ok) { throw new Error(data.error || 'Failed to connect Apple account'); } if (data.needs2FA) { // Show 2FA code input setNeeds2FA(true); } else { // Connected without 2FA if (onConnectionAdded && data.connection) { onConnectionAdded(data.connection); } setShowAppleModal(false); } } catch (err: any) { setAppleError(err.message || 'Connection failed'); } finally { setIsConnectingApple(false); } }; const submitSecurityCode = async () => { if (!securityCode || securityCode.length < 4) { setAppleError('Please enter a valid security code.'); return; } setIsConnectingApple(true); setAppleError(''); try { const response = await fetch('/api/reminders/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: appleEmail, code: securityCode, password: applePassword }), }); const data = await response.json(); if (!response.ok) { throw new Error(data.error || 'Verification failed'); } setShowAppleModal(false); // Refresh the page to pick up the new connection window.location.reload(); } catch (err: any) { setAppleError(err.message || 'Verification failed'); } finally { setIsConnectingApple(false); } }; // Function to trigger manual sync const handleManualSync = useCallback(async (connectionId: string) => { setIsSyncing(prev => ({ ...prev, [connectionId]: true })); try { // Call the API endpoint for manual sync const response = await fetch('/api/calendar/sync', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ connectionId, timeMin: new Date().toISOString(), timeMax: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(), // Next 7 days }), }); const result = await response.json(); if (result.success) { // Update last sync time setLastSyncTime(prev => ({ ...prev, [connectionId]: new Date() })); // Notify parent component if (onSyncTriggered) { onSyncTriggered(connectionId); } } else { console.error('Sync failed:', result.error); alert(`Sync failed: ${result.error || 'Unknown error'}`); } } catch (error) { console.error('Sync error:', error); alert('Sync failed due to network error'); } finally { setIsSyncing(prev => ({ ...prev, [connectionId]: false })); } }, [onSyncTriggered]); // Function to remove connection with confirmation const handleRemoveConnection = useCallback((connectionId: string) => { setShowConfirmation(connectionId); }, []); // Confirm removal const confirmRemoveConnection = useCallback((connectionId: string) => { if (onConnectionRemoved) { onConnectionRemoved(connectionId); } setShowConfirmation(null); }, [onConnectionRemoved]); // Cancel removal const cancelRemoveConnection = useCallback(() => { setShowConfirmation(null); }, []); return (

Calendar Connections

{connections.length === 0 ? (

No calendar connections found.

Connect your Google or Apple Calendar to get started.

) : (
{connections.map(connection => (
{connection.provider === 'google' ? ( ) : ( )}

{connection.provider.charAt(0).toUpperCase() + connection.provider.slice(1)} Calendar

{connection.calendars.length} calendar{connection.calendars.length !== 1 ? 's' : ''} connected
Last sync: {formatDate(lastSyncTime[connection.id])}
{showConfirmation === connection.id ? (
) : ( )}
))}
) }

Add More Calendars

{/* Apple Calendar Connection Modal */} { showAppleModal && (

Connect Apple Account

{!needs2FA ? ( <>

Enter your Apple ID and password to connect your iCloud Calendar and Reminders. A security code will be sent to your Apple devices for verification.

{appleError && (
{appleError}
)}
setAppleEmail(e.target.value)} className="w-full border border-gray-300 rounded px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none" placeholder="name@icloud.com" />
setApplePassword(e.target.value)} className="w-full border border-gray-300 rounded px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none" placeholder="Enter your Apple ID password" />
) : ( <>

A security code has been sent to your Apple devices. Please enter the 6-digit code below to complete the connection.

{appleError && (
{appleError}
)}
setSecurityCode(e.target.value.replace(/\D/g, '').slice(0, 6))} className="w-full border border-gray-300 rounded px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none text-center text-2xl tracking-widest" placeholder="000000" maxLength={6} autoFocus />
) }
) }
); }; export default CalendarSettings;