import React, { useEffect, useState } from 'react'; import { CondoService } from '../services/mockDb'; import { AppSettings, Family, User, AlertDefinition, Condo, Notice, NoticeIconType, NoticeRead } from '../types'; import { Save, Building, Coins, Plus, Pencil, Trash2, X, CalendarCheck, AlertTriangle, User as UserIcon, Server, Bell, Clock, FileText, Lock, Megaphone, CheckCircle2, Info, Hammer, Link as LinkIcon, Eye, Calendar, List, UserCog, Mail, Power, MapPin, CreditCard, ToggleLeft, ToggleRight, LayoutGrid, PieChart, Users, Send, Cloud, HardDrive, ChevronRight, Palette, Monitor, Sun, Moon, Check } from 'lucide-react'; const PALETTES = [ { name: 'Blue (Standard)', color: '#2563eb' }, { name: 'Indigo', color: '#4f46e5' }, { name: 'Emerald', color: '#059669' }, { name: 'Rose', color: '#e11d48' }, { name: 'Amber', color: '#d97706' }, { name: 'Slate', color: '#475569' }, { name: 'Purple', color: '#9333ea' } ]; export const SettingsPage: React.FC = () => { const currentUser = CondoService.getCurrentUser(); const isSuperAdmin = currentUser?.role === 'admin'; const isPrivileged = currentUser?.role === 'admin' || currentUser?.role === 'poweruser'; type TabType = 'profile' | 'features' | 'branding' | 'general' | 'storage' | 'condos' | 'families' | 'users' | 'notices' | 'alerts'; const [activeTab, setActiveTab] = useState(isPrivileged ? 'general' : 'profile'); const [loading, setLoading] = useState(true); // Profile State const [profileForm, setProfileForm] = useState({ name: currentUser?.name || '', phone: currentUser?.phone || '', password: '', receiveAlerts: currentUser?.receiveAlerts ?? true, theme: localStorage.getItem('app-theme') || 'light' }); const [profileSaving, setProfileSaving] = useState(false); const [profileMsg, setProfileMsg] = useState(''); // Branding State const [brandingForm, setBrandingForm] = useState({ appName: '', appIcon: '', loginBg: '', primaryColor: '#2563eb' }); const [activeCondo, setActiveCondo] = useState(undefined); const [globalSettings, setGlobalSettings] = useState(null); const [condos, setCondos] = useState([]); const [showCondoModal, setShowCondoModal] = useState(false); const [editingCondo, setEditingCondo] = useState(null); const [condoForm, setCondoForm] = useState({ name: '', address: '', streetNumber: '', city: '', province: '', zipCode: '', notes: '', paypalClientId: '', defaultMonthlyQuota: 100, dueDay: 10 }); const [saving, setSaving] = useState(false); const [successMsg, setSuccessMsg] = useState(''); const [families, setFamilies] = useState([]); const [showFamilyModal, setShowFamilyModal] = useState(false); const [editingFamily, setEditingFamily] = useState(null); const [familyForm, setFamilyForm] = useState({ name: '', unitNumber: '', stair: '', floor: '', notes: '', contactEmail: '', customMonthlyQuota: '' }); const [users, setUsers] = useState([]); const [showUserModal, setShowUserModal] = useState(false); const [editingUser, setEditingUser] = useState(null); const [userForm, setUserForm] = useState({ name: '', email: '', password: '', phone: '', role: 'user', familyId: '', receiveAlerts: true }); const [alerts, setAlerts] = useState([]); const [showAlertModal, setShowAlertModal] = useState(false); const [editingAlert, setEditingAlert] = useState(null); const [alertForm, setAlertForm] = useState>({ subject: '', body: '', daysOffset: 1, offsetType: 'before_next_month', sendHour: 9, active: true }); const [showSmtpModal, setShowSmtpModal] = useState(false); const [testingSmtp, setTestingSmtp] = useState(false); const [testSmtpMsg, setTestSmtpMsg] = useState(''); const [notices, setNotices] = useState([]); const [showNoticeModal, setShowNoticeModal] = useState(false); const [editingNotice, setEditingNotice] = useState(null); const [noticeTargetMode, setNoticeTargetMode] = useState<'all' | 'specific'>('all'); const [noticeForm, setNoticeForm] = useState<{ title: string; content: string; type: 'info' | 'warning' | 'maintenance' | 'event'; link: string; condoId: string; active: boolean; targetFamilyIds: string[]; }>({ title: '', content: '', type: 'info', link: '', condoId: '', active: true, targetFamilyIds: [] }); const [noticeReadStats, setNoticeReadStats] = useState>({}); const [showReadDetailsModal, setShowReadDetailsModal] = useState(false); const [selectedNoticeId, setSelectedNoticeId] = useState(null); useEffect(() => { const fetchData = async () => { try { const activeC = await CondoService.getActiveCondo(); setActiveCondo(activeC); if (isPrivileged) { const condoList = await CondoService.getCondos(); const gSettings = await CondoService.getSettings(); setCondos(condoList); setGlobalSettings(gSettings); setBrandingForm({ appName: gSettings.branding?.appName || 'CondoPay', appIcon: gSettings.branding?.appIcon || '', loginBg: gSettings.branding?.loginBg || '', primaryColor: gSettings.branding?.primaryColor || '#2563eb' }); if (activeC) { setFamilies(await CondoService.getFamilies(activeC.id)); setUsers(await CondoService.getUsers(activeC.id)); setAlerts(await CondoService.getAlerts(activeC.id)); const allNotices = await CondoService.getNotices(activeC.id); setNotices(allNotices); const stats: Record = {}; for (const n of allNotices) { try { stats[n.id] = await CondoService.getNoticeReadStatus(n.id); } catch(e) {} } setNoticeReadStats(stats); } } } catch(e) { console.error(e); } finally { setLoading(false); } }; fetchData(); }, [isPrivileged]); const handleProfileSubmit = async (e: React.FormEvent) => { e.preventDefault(); setProfileSaving(true); setProfileMsg(''); try { await CondoService.updateProfile(profileForm); // Apply theme localStorage.setItem('app-theme', profileForm.theme); if (profileForm.theme === 'dark') document.documentElement.classList.add('dark'); else document.documentElement.classList.remove('dark'); setProfileMsg('Profilo aggiornato!'); setTimeout(() => setProfileMsg(''), 3000); } catch (e) { setProfileMsg('Errore'); } finally { setProfileSaving(false); } }; const handleBrandingSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!globalSettings) return; setSaving(true); try { const updated = { ...globalSettings, branding: brandingForm }; await CondoService.updateSettings(updated); setGlobalSettings(updated); setSuccessMsg('Branding aggiornato!'); window.dispatchEvent(new Event('branding-updated')); // Apply color immediately to UI document.documentElement.style.setProperty('--primary-color', brandingForm.primaryColor); setTimeout(() => setSuccessMsg(''), 3000); } catch(e) { console.error(e); } finally { setSaving(false); } }; // --- CRUD Handlers (Simplified for brevity as logic is unchanged) --- const handleGeneralSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!activeCondo) return; setSaving(true); try { await CondoService.saveCondo(activeCondo); setSuccessMsg('Aggiornato!'); setTimeout(() => setSuccessMsg(''), 3000); } catch (e) {} finally { setSaving(false); } }; const handleFeaturesSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!globalSettings) return; setSaving(true); try { await CondoService.updateSettings(globalSettings); setSuccessMsg('Salvato!'); window.location.reload(); } catch (e) {} finally { setSaving(false); } }; const handleSmtpSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!globalSettings) return; setSaving(true); try { await CondoService.updateSettings(globalSettings); setShowSmtpModal(false); } catch (e) {} finally { setSaving(false); } }; const handleStorageSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!globalSettings) return; setSaving(true); try { await CondoService.updateSettings(globalSettings); setSuccessMsg('Salvato!'); } catch (e) {} finally { setSaving(false); } }; const handleCondoSubmit = async (e: React.FormEvent) => { e.preventDefault(); try { await CondoService.saveCondo({ id: editingCondo?.id || '', ...condoForm }); setCondos(await CondoService.getCondos()); setShowCondoModal(false); } catch (e) {} }; const handleDeleteCondo = async (id: string) => { if(!confirm("Eliminare?")) return; await CondoService.deleteCondo(id); setCondos(await CondoService.getCondos()); }; const handleFamilySubmit = async (e: React.FormEvent) => { e.preventDefault(); try { const quota = familyForm.customMonthlyQuota ? parseFloat(familyForm.customMonthlyQuota) : undefined; if (editingFamily) { await CondoService.updateFamily({ ...editingFamily, ...familyForm, customMonthlyQuota: quota }); } else { await CondoService.addFamily({ ...familyForm, customMonthlyQuota: quota }); } setFamilies(await CondoService.getFamilies(activeCondo?.id)); setShowFamilyModal(false); } catch (e) {} }; const handleDeleteFamily = async (id: string) => { if(!confirm("Eliminare?")) return; await CondoService.deleteFamily(id); setFamilies(families.filter(f => f.id !== id)); }; const handleUserSubmit = async (e: React.FormEvent) => { e.preventDefault(); try { if (editingUser) await CondoService.updateUser(editingUser.id, userForm); else await CondoService.createUser(userForm); setUsers(await CondoService.getUsers(activeCondo?.id)); setShowUserModal(false); } catch (e) {} }; const handleDeleteUser = async (id: string) => { if(!confirm("Eliminare?")) return; await CondoService.deleteUser(id); setUsers(users.filter(u => u.id !== id)); }; const handleNoticeSubmit = async (e: React.FormEvent) => { e.preventDefault(); try { const now = new Date(); const sqlDate = now.toISOString().slice(0, 19).replace('T', ' '); await CondoService.saveNotice({ id: editingNotice?.id || '', ...noticeForm, targetFamilyIds: noticeTargetMode === 'all' ? [] : noticeForm.targetFamilyIds, date: editingNotice ? editingNotice.date : sqlDate }); setNotices(await CondoService.getNotices(activeCondo?.id)); setShowNoticeModal(false); } catch (e) {} }; const handleDeleteNotice = async (id: string) => { if(!confirm("Eliminare?")) return; await CondoService.deleteNotice(id); setNotices(notices.filter(n => n.id !== id)); }; const handleAlertSubmit = async (e: React.FormEvent) => { e.preventDefault(); try { await CondoService.saveAlert({ id: editingAlert?.id || '', ...alertForm } as any); setAlerts(await CondoService.getAlerts(activeCondo?.id)); setShowAlertModal(false); } catch (e) {} }; const handleDeleteAlert = async (id: string) => { if(!confirm("Eliminare?")) return; await CondoService.deleteAlert(id); setAlerts(alerts.filter(a => a.id !== id)); }; const tabs: {id: TabType, label: string, icon: React.ReactNode}[] = [ { id: 'profile', label: 'Profilo & Tema', icon: }, ]; if (isSuperAdmin) { tabs.push({ id: 'features', label: 'Funzionalità', icon: }); tabs.push({ id: 'branding', label: 'Personalizzazione', icon: }); } if (isPrivileged) { tabs.push({ id: 'general', label: 'Condominio', icon: }); if (globalSettings?.features.documents) tabs.push({ id: 'storage', label: 'Storage', icon: }); if (globalSettings?.features.multiCondo) tabs.push({ id: 'condos', label: 'Condomini', icon: }); tabs.push({ id: 'families', label: 'Famiglie', icon: }, { id: 'users', label: 'Utenti', icon: }); if (globalSettings?.features.notices) tabs.push({ id: 'notices', label: 'Bacheca', icon: }); tabs.push({ id: 'alerts', label: 'Avvisi', icon: }); } if (loading) return
Caricamento...
; return (

Impostazioni

{activeCondo ? `Gestione: ${activeCondo.name}` : 'Pannello di Controllo'}

{tabs.map(tab => ( ))}
{activeTab === 'profile' && (

Profilo & Preferenze

setProfileForm({...profileForm, name: e.target.value})} className="w-full border p-2.5 rounded-lg text-slate-700 dark:bg-slate-700 dark:text-slate-100"/>
setProfileForm({...profileForm, phone: e.target.value})} className="w-full border p-2.5 rounded-lg text-slate-700 dark:bg-slate-700 dark:text-slate-100"/>
setProfileForm({...profileForm, password: e.target.value})} className="w-full border p-2.5 rounded-lg text-slate-700 dark:bg-slate-700 dark:text-slate-100"/>
{profileMsg &&

{profileMsg}

}
)} {activeTab === 'branding' && isSuperAdmin && (

Personalizzazione Piattaforma

setBrandingForm({...brandingForm, appName: e.target.value})} placeholder="Es: MyCondo Manager" />
setBrandingForm({...brandingForm, appIcon: e.target.value})} placeholder="https://image.com/logo.png" />
setBrandingForm({...brandingForm, loginBg: e.target.value})} placeholder="https://image.com/bg.jpg" />
{PALETTES.map(p => ( ))}
setBrandingForm({...brandingForm, primaryColor: e.target.value})} className="h-10 w-10 border-none bg-transparent cursor-pointer" /> Scegli un colore personalizzato ({brandingForm.primaryColor})
{successMsg &&

{successMsg}

}
)} {activeTab === 'features' && isSuperAdmin && globalSettings && (

Funzionalità Piattaforma

{Object.keys(globalSettings.features).map((key) => (

{key.replace(/([A-Z])/g, ' $1')}

))}
)} {activeTab === 'general' && isPrivileged && activeCondo && (

Dati Condominio

setActiveCondo({...activeCondo, name: e.target.value})} placeholder="Nome" required />
setActiveCondo({...activeCondo, address: e.target.value})} placeholder="Indirizzo" required /> setActiveCondo({...activeCondo, city: e.target.value})} placeholder="Città" required />
setActiveCondo({...activeCondo, defaultMonthlyQuota: parseFloat(e.target.value)})} required />
setActiveCondo({...activeCondo, dueDay: parseInt(e.target.value)})} required />
)}
); };