import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation } from '@tanstack/react-query';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Globe, Tag, Plus, Edit, Trash2, Layers, User as UserIcon, ShieldCheck, Share2, Server, Copy, Settings as SettingsIcon, Bell, Loader2, Clock } from 'lucide-react';
import { Switch } from '@/components/ui/switch';
import { ShareAccessModal } from '@/components/ShareAccessModal';
import { ChangePasswordModal } from '@/components/ChangePasswordModal';
import { UpdateProfileModal } from '@/components/UpdateProfileModal';
import { ShareLabelModal } from '@/components/ShareLabelModal';
import { Label } from '@shared/schema';
import { User } from '@shared/schema';
import { queryClient, apiRequest } from '@/lib/queryClient';
import { useToast } from '@/hooks/use-toast';
import { useLocation } from "wouter";
import { useNotifications } from '@/hooks/use-notifications';
import { DataExportCard } from '@/components/user/DataExportCard';
const NotificationSettings = () => {
const { t } = useTranslation();
const { toast } = useToast();
const {
enabled,
toggleEnabled,
permission,
requestPermission,
pushSupported,
isStandalone,
sendTestNotification,
isLoading
} = useNotifications({ poll: false });
const handleToggle = async (checked: boolean) => {
if (checked && permission !== 'granted') {
const success = await requestPermission();
if (success) {
toast({
title: t('notifications.enabledTitle'),
description: t('notifications.enabledBody'),
});
}
} else {
await toggleEnabled(checked);
}
};
const handleTestNotification = async () => {
const success = await sendTestNotification();
if (success) {
toast({
title: t('notifications.testSent', 'Test Sent'),
description: t('notifications.testSentDesc', 'Check for a notification on your device.'),
});
} else {
toast({
title: t('common.error'),
description: t('notifications.testFailed', 'Failed to send test notification.'),
variant: 'destructive',
});
}
};
return (
{/* Push Support Status */}
{pushSupported && (
{t('notifications.pushSupported', 'Push Supported')}
{isStandalone && (
{t('notifications.installedApp', 'Installed App')}
)}
)}
{/* iOS PWA Hint */}
{!pushSupported && /iPhone|iPad|iPod/.test(navigator.userAgent) && !isStandalone && (
{t('notifications.iosHintTitle', 'Add to Home Screen')}
{t('notifications.iosHintDesc', 'To receive push notifications on iOS, tap the Share button and select "Add to Home Screen", then open the app from there.')}
)}
{/* Main Toggle */}
{pushSupported
? t('notifications.enablePush', 'Push Notifications')
: t('notifications.enableBrowser')}
{permission === 'denied' ? (
{t('notifications.permissionDenied', 'Permission denied by browser. Please reset site permissions.')}
) : pushSupported ? (
t('notifications.pushDescription', 'Receive notifications even when the app is closed.')
) : (
t('notifications.description')
)}
{/* Test Button */}
{enabled && pushSupported && (
{t('notifications.sendTest', 'Send Test Notification')}
)}
);
};
const ScheduleSettings = ({ user }: { user: User }) => {
const { t } = useTranslation();
const { toast } = useToast();
const [activeTab, setActiveTab] = useState<'work' | 'personal'>('work');
// Helper to safely get availability data
const getAvailability = (type: 'work' | 'personal') => {
// Cast to any because TS might not know about the JSON structure fully yet if types aren't perfectly synced in IDE
const avail = user.availability as any;
if (avail && avail[type]) {
return avail[type];
}
// Fallback defaults
if (type === 'work') return user.workHours || { start: "09:00", end: "17:00", days: [1, 2, 3, 4, 5] };
return { start: "18:00", end: "22:00", days: [1, 2, 3, 4, 5, 0, 6] };
};
// State for both schedules
const [workSchedule, setWorkSchedule] = useState(getAvailability('work'));
const [personalSchedule, setPersonalSchedule] = useState(getAvailability('personal'));
const currentSchedule = activeTab === 'work' ? workSchedule : personalSchedule;
const setCurrentSchedule = (newSched: any) => {
if (activeTab === 'work') setWorkSchedule(newSched);
else setPersonalSchedule(newSched);
};
const updateScheduleMutation = useMutation({
mutationFn: async () => {
const payload = {
availability: {
work: workSchedule,
personal: personalSchedule
}
};
const res = await apiRequest("PATCH", "/api/user/schedule", payload);
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/user"] });
toast({ title: t('settings.schedule.saved') });
}
});
const toggleDay = (day: number) => {
const currentDays = currentSchedule.days || [];
let newDays;
if (currentDays.includes(day)) {
newDays = currentDays.filter((d: number) => d !== day);
} else {
newDays = [...currentDays, day].sort();
}
setCurrentSchedule({ ...currentSchedule, days: newDays });
};
const handleChange = (field: 'start' | 'end', value: string) => {
setCurrentSchedule({ ...currentSchedule, [field]: value });
};
const handleSave = () => {
updateScheduleMutation.mutate();
};
const days = [
{ id: 1, label: t('analytics.mon') },
{ id: 2, label: t('analytics.tue') },
{ id: 3, label: t('analytics.wed') },
{ id: 4, label: t('analytics.thu') },
{ id: 5, label: t('analytics.fri') },
{ id: 6, label: t('analytics.sat') },
{ id: 0, label: t('analytics.sun') },
];
return (
setActiveTab('work')}
>
{t('settings.schedule.work', 'Work Schedule')}
setActiveTab('personal')}
>
{t('settings.schedule.personal', 'Personal Schedule')}
{t('settings.schedule.days')}
{days.map(day => (
toggleDay(day.id)}
className="w-12 h-12 rounded-full p-0"
>
{day.label.slice(0, 2)}
))}
{activeTab === 'work'
? t('settings.schedule.workDesc', "Tasks with 'Work' labels will be scheduled during these hours.")
: t('settings.schedule.personalDesc', "Tasks with 'Personal' labels will be scheduled during these hours. 'Neutral' tasks can use either.")}
{updateScheduleMutation.isPending ? t('common.loading') : t('common.save')}
);
};
interface SettingsProps {
onNavigateToTemplates: () => void;
}
export default function Settings({ onNavigateToTemplates }: SettingsProps) {
const { t, i18n } = useTranslation();
const { toast } = useToast();
const [, setLocation] = useLocation();
// Fetch user
const { data: user, isLoading: isLoadingUser } = useQuery({
queryKey: ['/api/user']
});
if (isLoadingUser) {
return (
);
}
if (!user) {
return (
{t('common.loginRequired')}
setLocation('/')}>
{t('auth.login')}
);
}
const [isLabelDialogOpen, setIsLabelDialogOpen] = useState(false);
const [editingLabel, setEditingLabel] = useState(null);
const [labelName, setLabelName] = useState('');
const [labelColor, setLabelColor] = useState('#3B82F6');
const [labelDomain, setLabelDomain] = useState('neutral');
const [isShareAccessOpen, setIsShareAccessOpen] = useState(false);
const [isShareLabelOpen, setIsShareLabelOpen] = useState(false);
const [sharingLabel, setSharingLabel] = useState(null);
const [isChangePasswordOpen, setIsChangePasswordOpen] = useState(false);
const [isUpdateProfileOpen, setIsUpdateProfileOpen] = useState(false);
const handleLanguageChange = (value: string) => {
i18n.changeLanguage(value);
localStorage.setItem('taskflow-language', value);
// Persist to DB
privacyMutation.mutate({ language: value } as any);
console.log('Language changed to:', value);
};
const privacyMutation = useMutation({
mutationFn: async (updates: { showOnLeaderboard?: boolean; isSearchable?: boolean; aiEnabled?: boolean }) => {
const res = await apiRequest("PATCH", "/api/user/privacy", updates);
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/user"] });
toast({ title: "Settings updated" });
},
});
const handlePrivacyUpdate = (updates: { showOnLeaderboard?: boolean; isSearchable?: boolean; aiEnabled?: boolean }) => {
privacyMutation.mutate(updates);
};
// 2FA Logic
const [is2FADialogOpen, setIs2FADialogOpen] = useState(false);
const [otpCode, setOtpCode] = useState("");
const [debugCode, setDebugCode] = useState(null);
const generate2FAMutation = useMutation({
mutationFn: async () => {
const res = await apiRequest("POST", "/api/auth/2fa/generate");
return res.json();
},
onSuccess: (data) => {
setDebugCode(data.debugCode); // For dev convenience
setIs2FADialogOpen(true);
toast({ title: t('auth.2faCodeSent'), description: t('auth.checkEmail') });
},
onError: (err: Error) => {
toast({ title: "Failed to start 2FA setup", description: err.message, variant: "destructive" });
}
});
const verify2FAMutation = useMutation({
mutationFn: async (code: string) => {
const res = await apiRequest("POST", "/api/auth/verify-2fa", { userId: user.id, code });
return res.json();
},
onSuccess: () => {
setIs2FADialogOpen(false);
setOtpCode("");
queryClient.invalidateQueries({ queryKey: ["/api/user"] });
toast({ title: "2FA Enabled Successfully" });
},
onError: (err: Error) => {
toast({ title: "Verification failed", description: err.message, variant: "destructive" });
}
});
const disable2FAMutation = useMutation({
mutationFn: async () => {
await apiRequest("POST", "/api/auth/2fa/disable");
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/user"] });
toast({ title: "2FA Disabled" });
}
});
const handle2FAToggle = (checked: boolean) => {
if (checked) {
generate2FAMutation.mutate(); // Starts flow, opens dialog on success
} else {
if (confirm("Are you sure you want to disable 2FA? This will reduce your account security.")) {
disable2FAMutation.mutate();
}
}
};
// Fetch labels
const { data: labelsData, isLoading: labelsLoading } = useQuery({
queryKey: ['/api/labels']
});
const labels = labelsData ?? [];
// Create label mutation
const createLabelMutation = useMutation({
mutationFn: (data: { name: string; color: string; domain: string }) =>
apiRequest('POST', '/api/labels', data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['/api/labels'] });
setIsLabelDialogOpen(false);
setLabelName('');
setLabelColor('#3B82F6');
setLabelDomain('neutral');
toast({
title: t('settings.labels.created'),
description: t('settings.labels.createdDescription'),
});
},
});
// Update label mutation
const updateLabelMutation = useMutation({
mutationFn: ({ id, ...data }: { id: string; name: string; color: string; domain: string }) =>
apiRequest('PATCH', `/api/labels/${id}`, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['/api/labels'] });
setIsLabelDialogOpen(false);
setEditingLabel(null);
setLabelName('');
setLabelColor('#3B82F6');
setLabelDomain('neutral');
toast({
title: t('settings.labels.updated'),
description: t('settings.labels.updatedDescription'),
});
},
});
// Delete label mutation
const deleteLabelMutation = useMutation({
mutationFn: (id: string) => apiRequest('DELETE', `/api/labels/${id}`),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['/api/labels'] });
toast({
title: t('settings.labels.deleted'),
description: t('settings.labels.deletedDescription'),
});
},
});
const handleSaveLabel = () => {
if (!labelName.trim()) return;
if (editingLabel) {
updateLabelMutation.mutate({
id: editingLabel.id,
name: labelName,
color: labelColor,
domain: labelDomain,
});
} else {
createLabelMutation.mutate({ name: labelName, color: labelColor, domain: labelDomain });
}
};
const handleEditLabel = (label: Label) => {
setEditingLabel(label);
setLabelName(label.name);
setLabelColor(label.color);
setLabelDomain(label.domain || 'neutral');
setIsLabelDialogOpen(true);
};
const handleDeleteLabel = (id: string) => {
if (confirm(t('settings.labels.deleteConfirm'))) {
deleteLabelMutation.mutate(id);
}
};
const handleShareLabel = (label: Label) => {
setSharingLabel(label);
setIsShareLabelOpen(true);
};
const generateApiKeyMutation = useMutation({
mutationFn: async () => {
const res = await apiRequest("POST", "/api/user/apikey", {});
return res.json();
},
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ["/api/user"] });
toast({ title: t('settings.mcp.generated') });
},
});
const revokeApiKeyMutation = useMutation({
mutationFn: async () => {
await apiRequest("DELETE", "/api/user/apikey");
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/user"] });
toast({ title: t('settings.mcp.revoked') });
},
});
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text);
toast({ title: "Copied!" });
}
return (
{t('settings.title')}
{/* Account Settings */}
{t('settings.account.title')}
{t('settings.account.description')}
{t('settings.account.username')}
{user?.username || t('common.loading')}
{t('auth.email')}
{user?.email || 'No email set'}
setIsUpdateProfileOpen(true)} data-testid="button-edit-email">
{user?.role === 'admin' && (
{t('settings.account.userId')}
{user?.id || '...'}
)}
setIsChangePasswordOpen(true)} data-testid="button-change-password">
{t('auth.changePassword')}
{user && (
<>
>
)}
{/* Notifications Settings */}
{t('notifications.title')}
{t('notifications.description')}
{/* Social & Privacy */}
{t('settings.social.title')}
{t('settings.social.description')}
{t('settings.social.publicLeaderboard')}
{t('settings.social.publicLeaderboardDesc')}
handlePrivacyUpdate({ showOnLeaderboard: checked })}
/>
{t('settings.social.searchable')}
{t('settings.social.searchableDesc')}
handlePrivacyUpdate({ isSearchable: checked })}
/>
{t('settings.ai.enableUser')}
{t('settings.ai.enableUserDesc')}
handlePrivacyUpdate({ aiEnabled: checked })}
/>
{t('settings.social.2fa')}
{t('settings.social.2faDesc')}
handle2FAToggle(checked)}
disabled={generate2FAMutation.isPending || disable2FAMutation.isPending}
/>
{t('auth.verify2FATitle', 'Verify 2FA')}
Enter the code sent to your email to enable 2FA.
{debugCode && Debug Code: {debugCode}
}
setOtpCode(e.target.value.replace(/\D/g, ''))}
/>
verify2FAMutation.mutate(otpCode)}
disabled={verify2FAMutation.isPending || otpCode.length !== 6}
>
{verify2FAMutation.isPending ? "Verifying..." : "Verify & Enable"}
setIsShareAccessOpen(true)}>
{t('settings.social.shareAccess')}
{/* Schedule Settings */}
{t('settings.schedule.title')}
{t('settings.schedule.description')}
{user && }
{/* Language Settings */}
{t('settings.language.title')}
{t('settings.language.description')}
{t('settings.language.english')}
{t('settings.language.german')}
{/* Labels Management */}
{t('settings.labels.title')}
{t('settings.labels.description')}
{t('settings.labels.createLabel')}
{editingLabel ? t('settings.labels.editLabel') : t('settings.labels.createNewLabel')}
setLabelName(e.target.value)}
data-testid="input-label-name"
/>
Work
Personal
Neutral
Used for smart scheduling.
{
setIsLabelDialogOpen(false);
setEditingLabel(null);
setLabelName('');
setLabelColor('#3B82F6');
setLabelDomain('neutral');
}}
className="flex-1"
data-testid="button-cancel-label"
>
{t('settings.labels.cancel')}
{editingLabel ? t('settings.labels.update') : t('settings.labels.create')}
{labelsLoading ? (
{t('settings.labels.loading')}
) : (
{labels.map((label) => (
{label.name}
{label.domain || 'neutral'}
{label.creatorId === user?.id && (
handleShareLabel(label)}
title={t('settings.labels.share')}
>
)}
handleEditLabel(label)}
className="w-6 h-6"
data-testid={`button-edit-${label.id}`}
>
handleDeleteLabel(label.id)}
className="w-6 h-6 text-destructive hover:text-destructive"
data-testid={`button-delete-${label.id}`}
>
))}
{labels.length === 0 && (
{t('settings.labels.noLabels')}
{t('settings.labels.noLabelsDescription')}
setIsLabelDialogOpen(true)}
data-testid="button-create-first-label"
>
{t('settings.labels.createLabel')}
)}
)}
{/* Project Templates */}
{t('settings.templates.title')}
{t('settings.templates.description')}
{t('settings.templates.manageTemplates')}
{/* Data Export */}
{/* Admin Section */}
{
user?.role === 'admin' && (
{t('settings.admin.title')}
{t('settings.admin.description')}
setLocation('/admin/users')}>
{t('settings.admin.manageUsers')}
setLocation('/admin/settings')}>
{t('settings.admin.systemSettings')}
)
}
);
}