import { useState, useEffect, useRef, useCallback } from 'react'; import { toast } from 'sonner'; import { useQueryClient } from '@tanstack/react-query'; import { Settings, User, Palette, Cloud, CalendarDays, LayoutDashboard, MapPin, X, Search, Loader2, } from 'lucide-react'; import { useSettings } from '@/hooks/useSettings'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { cn } from '@/lib/utils'; import api from '@/lib/api'; import type { GeoLocation } from '@/types'; const accentColors = [ { name: 'cyan', label: 'Cyan', color: '#06b6d4' }, { name: 'blue', label: 'Blue', color: '#3b82f6' }, { name: 'purple', label: 'Purple', color: '#8b5cf6' }, { name: 'orange', label: 'Orange', color: '#f97316' }, { name: 'green', label: 'Green', color: '#22c55e' }, ]; export default function SettingsPage() { const queryClient = useQueryClient(); const { settings, updateSettings, isUpdating } = useSettings(); const [selectedColor, setSelectedColor] = useState(settings?.accent_color || 'cyan'); const [upcomingDays, setUpcomingDays] = useState(settings?.upcoming_days || 7); const [preferredName, setPreferredName] = useState(settings?.preferred_name ?? ''); const [locationQuery, setLocationQuery] = useState(''); const [locationResults, setLocationResults] = useState([]); const [isSearching, setIsSearching] = useState(false); const [showDropdown, setShowDropdown] = useState(false); const searchRef = useRef(null); const debounceRef = useRef>(); const [firstDayOfWeek, setFirstDayOfWeek] = useState(settings?.first_day_of_week ?? 0); // Sync state when settings load useEffect(() => { if (settings) { setSelectedColor(settings.accent_color); setUpcomingDays(settings.upcoming_days); setPreferredName(settings.preferred_name ?? ''); setFirstDayOfWeek(settings.first_day_of_week); } }, [settings?.id]); // only re-sync on initial load (settings.id won't change) const hasLocation = settings?.weather_lat != null && settings?.weather_lon != null; const searchLocations = useCallback(async (query: string) => { if (query.length < 2) { setLocationResults([]); setShowDropdown(false); return; } setIsSearching(true); try { const { data } = await api.get('/weather/search', { params: { q: query } }); setLocationResults(data); setShowDropdown(data.length > 0); } catch { setLocationResults([]); setShowDropdown(false); } finally { setIsSearching(false); } }, []); const handleLocationInputChange = (value: string) => { setLocationQuery(value); if (debounceRef.current) clearTimeout(debounceRef.current); debounceRef.current = setTimeout(() => searchLocations(value), 300); }; const handleLocationSelect = async (loc: GeoLocation) => { const displayName = [loc.name, loc.state, loc.country].filter(Boolean).join(', '); setShowDropdown(false); setLocationQuery(''); setLocationResults([]); try { await updateSettings({ weather_city: displayName, weather_lat: loc.lat, weather_lon: loc.lon, }); queryClient.invalidateQueries({ queryKey: ['weather'] }); toast.success(`Weather location set to ${displayName}`); } catch { toast.error('Failed to update weather location'); } }; const handleLocationClear = async () => { try { await updateSettings({ weather_city: null, weather_lat: null, weather_lon: null }); queryClient.invalidateQueries({ queryKey: ['weather'] }); toast.success('Weather location cleared'); } catch { toast.error('Failed to clear weather location'); } }; // Close dropdown on outside click useEffect(() => { const handler = (e: MouseEvent) => { if (searchRef.current && !searchRef.current.contains(e.target as Node)) { setShowDropdown(false); } }; document.addEventListener('mousedown', handler); return () => document.removeEventListener('mousedown', handler); }, []); useEffect(() => { return () => { if (debounceRef.current) clearTimeout(debounceRef.current); }; }, []); const handleNameSave = async () => { const trimmed = preferredName.trim(); if (trimmed === (settings?.preferred_name || '')) return; try { await updateSettings({ preferred_name: trimmed || null }); toast.success('Name updated'); } catch { toast.error('Failed to update name'); } }; const handleColorChange = async (color: string) => { setSelectedColor(color); try { await updateSettings({ accent_color: color }); toast.success('Accent color updated'); } catch { toast.error('Failed to update accent color'); } }; const handleFirstDayChange = async (value: number) => { const previous = firstDayOfWeek; setFirstDayOfWeek(value); try { await updateSettings({ first_day_of_week: value }); queryClient.invalidateQueries({ queryKey: ['calendar-events'] }); toast.success(value === 0 ? 'Week starts on Sunday' : 'Week starts on Monday'); } catch { setFirstDayOfWeek(previous); toast.error('Failed to update first day of week'); } }; const handleUpcomingDaysSave = async () => { if (isNaN(upcomingDays) || upcomingDays < 1 || upcomingDays > 30) return; if (upcomingDays === settings?.upcoming_days) return; try { await updateSettings({ upcoming_days: upcomingDays }); toast.success('Settings updated'); } catch { toast.error('Failed to update settings'); } }; return (
{/* Page header — matches Stage 4-5 pages */}
{/* ── Left column: Profile, Appearance, Weather ── */}
{/* Profile */}
Profile Personalize how UMBRA greets you
setPreferredName(e.target.value)} onBlur={handleNameSave} onKeyDown={(e) => { if (e.key === 'Enter') handleNameSave(); }} maxLength={100} />

Used in the dashboard greeting, e.g. "Good morning, {preferredName || 'Kyle'}."

{/* Appearance */}
Appearance Customize the look and feel of your application
{accentColors.map((color) => ( ))}
{/* Weather */}
Weather Configure the weather widget on your dashboard
{hasLocation ? (
{settings?.weather_city || `${settings?.weather_lat}, ${settings?.weather_lon}`}
) : (
handleLocationInputChange(e.target.value)} onFocus={() => { if (locationResults.length > 0) setShowDropdown(true); }} className="pl-9 pr-9" /> {isSearching && ( )}
{showDropdown && (
{locationResults.map((loc, i) => ( ))}
)}
)}

Search and select your city for accurate weather data on the dashboard.

{/* ── Right column: Calendar, Dashboard ── */}
{/* Calendar */}
Calendar Configure your calendar preferences

Sets which day the calendar week starts on

{/* Dashboard */}
Dashboard Configure your dashboard preferences
setUpcomingDays(parseInt(e.target.value))} onBlur={handleUpcomingDaysSave} onKeyDown={(e) => { if (e.key === 'Enter') handleUpcomingDaysSave(); }} className="w-24" disabled={isUpdating} /> days

How many days ahead to show in the upcoming items widget

); }