'use client';
import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { AuthGuard } from '@/components/AuthGuard';
import { DashboardLayout } from '@/components/DashboardLayout';
import { userApi, gmailApi, smtpApi } from '@/lib/api';
import { useAuthStore } from '@/store/authStore';
import {
CheckCircle,
Loader2,
User,
Mail,
Shield,
Server,
AlertTriangle,
XCircle,
Bug,
RotateCcw,
Tags,
Send,
} from 'lucide-react';
const DEFAULT_GMAIL_IMPORT_LABEL_TEMPLATES = ['{{source_email}}', 'imported'];
function parseImportLabelTemplates(input: string): string[] {
return input
.split('\n')
.map((value) => value.trim())
.filter((value, index, values) => value.length > 0 && values.indexOf(value) === index);
}
function GmailImportLabelsForm({
gmailCredential,
onSave,
isSaving,
}: {
gmailCredential: {
gmail_email: string;
import_label_templates: string[];
default_import_label_templates: string[];
};
onSave: (labels: string[]) => void;
isSaving: boolean;
}) {
const [labelsInput, setLabelsInput] = useState(
gmailCredential.import_label_templates.join('\n')
);
const defaultTemplates =
gmailCredential.default_import_label_templates.length > 0
? gmailCredential.default_import_label_templates
: DEFAULT_GMAIL_IMPORT_LABEL_TEMPLATES;
const parsedLabels = parseImportLabelTemplates(labelsInput);
const isDefaultSelection =
parsedLabels.length === defaultTemplates.length &&
parsedLabels.every((value, index) => value === defaultTemplates[index]);
return (
Import labels
One label is created per line. We recommend keeping{' '}
{'{{source_email}}'}
{' '}
so each imported message is tagged with the mailbox it came from, plus a
catch-all label like imported .
Example: a mail pulled from billing@example.com will be
labeled as billing@example.com when{' '}
{'{{source_email}}'}
{' '}
is present.
);
}
export default function SettingsPage() {
return (
);
}
function SettingsContent() {
const queryClient = useQueryClient();
const { user, setUser } = useAuthStore();
const [profileForm, setProfileForm] = useState({
full_name: user?.full_name || '',
email: user?.email || '',
});
const [profileSaved, setProfileSaved] = useState(false);
// SMTP form state
const [smtpForm, setSmtpForm] = useState({
host: 'smtp.gmail.com',
port: 587,
username: '',
sender_email: '',
password: '',
use_tls: true,
});
const [smtpSaved, setSmtpSaved] = useState(false);
// Refresh user data from the server
const { data: currentUser } = useQuery({
queryKey: ['current-user'],
queryFn: userApi.getCurrentUser,
initialData: user ?? undefined,
});
// Gmail credential status
const {
data: gmailCredential,
isLoading: gmailLoading,
error: gmailError,
} = useQuery({
queryKey: ['gmail-credential'],
queryFn: gmailApi.getCredential,
retry: false,
});
// SMTP config
const { data: smtpConfig, isLoading: smtpLoading } = useQuery({
queryKey: ['smtp-config'],
queryFn: smtpApi.get,
retry: false,
});
// Pre-populate SMTP form when data loads
const [smtpFormPopulated, setSmtpFormPopulated] = useState(false);
if (smtpConfig && !smtpFormPopulated) {
setSmtpFormPopulated(true);
setSmtpForm((prev) => ({
...prev,
host: smtpConfig.host,
port: smtpConfig.port,
username: smtpConfig.username,
sender_email: smtpConfig.sender_email,
use_tls: smtpConfig.use_tls,
password: '', // never pre-fill password
}));
}
const updateProfileMutation = useMutation({
mutationFn: (data: { full_name: string; email: string }) =>
userApi.updateProfile(data),
onSuccess: (updatedUser) => {
setUser(updatedUser);
queryClient.invalidateQueries({ queryKey: ['current-user'] });
setProfileSaved(true);
setTimeout(() => setProfileSaved(false), 3000);
},
});
const disconnectGmailMutation = useMutation({
mutationFn: gmailApi.disconnect,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['gmail-credential'] });
},
});
const [debugEmailResult, setDebugEmailResult] = useState(null);
const [gmailLabelsSaved, setGmailLabelsSaved] = useState(false);
const sendDebugEmailMutation = useMutation({
mutationFn: gmailApi.sendDebugEmail,
onSuccess: () => {
setDebugEmailResult('success');
setTimeout(() => setDebugEmailResult(null), 5000);
},
onError: () => {
setDebugEmailResult('error');
setTimeout(() => setDebugEmailResult(null), 5000);
},
});
const updateGmailLabelsMutation = useMutation({
mutationFn: gmailApi.updateImportLabels,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['gmail-credential'] });
setGmailLabelsSaved(true);
setTimeout(() => setGmailLabelsSaved(false), 3000);
},
});
const saveSmtpMutation = useMutation({
mutationFn: smtpApi.save,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['smtp-config'] });
setSmtpSaved(true);
setTimeout(() => setSmtpSaved(false), 3000);
},
});
const deleteSmtpMutation = useMutation({
mutationFn: smtpApi.remove,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['smtp-config'] });
setSmtpForm({ host: 'smtp.gmail.com', port: 587, username: '', sender_email: '', password: '', use_tls: true });
},
});
const [smtpTestResult, setSmtpTestResult] = useState<{ success: boolean; message: string } | null>(null);
const testSmtpMutation = useMutation({
mutationFn: smtpApi.test,
onSuccess: (result) => {
setSmtpTestResult(result);
setTimeout(() => setSmtpTestResult(null), 6000);
},
onError: () => {
setSmtpTestResult({ success: false, message: 'Request failed. Check your network connection.' });
setTimeout(() => setSmtpTestResult(null), 6000);
},
});
const handleProfileChange = (e: React.ChangeEvent) => {
const { name, value } = e.target;
setProfileForm((prev) => ({ ...prev, [name]: value }));
};
const handleSmtpChange = (e: React.ChangeEvent) => {
const { name, value, type } = e.target;
setSmtpForm((prev) => ({
...prev,
[name]: type === 'checkbox' ? (e.target as HTMLInputElement).checked
: name === 'port' ? Number(value)
: value,
}));
};
const handleProfileSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
await updateProfileMutation.mutateAsync({
full_name: profileForm.full_name,
email: profileForm.email,
});
} catch (error) {
const errorMessage =
error instanceof Error && 'response' in error
? (error as { response?: { data?: { detail?: string } } }).response?.data
?.detail
: null;
alert(errorMessage || 'Failed to update profile');
}
};
const handleSmtpSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
await saveSmtpMutation.mutateAsync({
host: smtpForm.host,
port: smtpForm.port,
username: smtpForm.username,
sender_email: smtpForm.sender_email,
password: smtpForm.password || undefined,
use_tls: smtpForm.use_tls,
});
} catch (error) {
const errorMessage =
error instanceof Error && 'response' in error
? (error as { response?: { data?: { detail?: string } } }).response?.data
?.detail
: null;
alert(errorMessage || 'Failed to save SMTP settings');
}
};
const handleConnectGmail = async () => {
try {
const redirectUri = `${window.location.origin}/auth/callback`;
const url = await gmailApi.getAuthorizeUrl(redirectUri);
window.location.href = url;
} catch (error) {
const errorMessage =
error instanceof Error && 'response' in error
? (error as { response?: { data?: { detail?: string } } }).response?.data
?.detail
: null;
alert(errorMessage || 'Failed to start Gmail authorization');
}
};
const handleDisconnectGmail = async () => {
if (confirm('Disconnect Gmail? Mail accounts using Gmail API delivery will fall back to SMTP.')) {
try {
await disconnectGmailMutation.mutateAsync();
} catch {
alert('Failed to disconnect Gmail');
}
}
};
const displayUser = currentUser ?? user;
const gmailConnected = gmailCredential?.is_valid === true;
// gmail 404 just means "not connected yet" — not a real error
const gmailNotConnected = !gmailCredential && !gmailLoading;
return (
Settings
{/* Profile Section */}
{/* Gmail API Section */}
Gmail API Delivery
Grant this app permission to inject emails directly into your Gmail inbox.
This is the preferred delivery method — emails arrive with original headers
intact, bypassing SMTP entirely.
Token lifetime: Access tokens expire after 1 hour and are
refreshed automatically. Refresh tokens do not expire unless you revoke
access via your{' '}
Google Account permissions
. If revoked, click “Connect Gmail” again to re-authorise.
{gmailLoading && (
Checking Gmail connection…
)}
{!gmailLoading && gmailConnected && (
Connected as {gmailCredential.gmail_email}
{gmailCredential.last_verified_at && (
Last verified: {new Date(gmailCredential.last_verified_at).toLocaleString()}
)}
sendDebugEmailMutation.mutate()}
disabled={sendDebugEmailMutation.isPending}
title="Inject a test email into your Gmail inbox"
className="flex items-center gap-1.5 px-4 py-2 text-sm bg-amber-50 text-amber-700 rounded-md hover:bg-amber-100 transition-colors disabled:opacity-50"
>
{sendDebugEmailMutation.isPending ? (
<> Sending…>
) : (
<> Send Debug Email>
)}
Re-authorise
Disconnect
{debugEmailResult === 'success' && (
Debug email injected successfully. Check your Gmail inbox for the
configured import labels plus a test {' '}
label.
)}
{debugEmailResult === 'error' && (
Failed to inject debug email. Check that Gmail API access is still valid.
)}
updateGmailLabelsMutation.mutate(labels)}
/>
{gmailLabelsSaved && (
Gmail import labels saved.
)}
)}
{!gmailLoading && gmailCredential && !gmailCredential.is_valid && (
Gmail access was revoked. Click “Re-authorise” below to restore Gmail API delivery.
)}
{!gmailLoading && (gmailNotConnected || (gmailCredential && !gmailCredential.is_valid)) && (
{gmailError ? 'Connect Gmail' : 'Re-authorise Gmail'}
)}
{!gmailLoading && gmailNotConnected && (
No Gmail account connected yet.
)}
{/* SMTP Fallback Section */}
SMTP Fallback
Used when Gmail API is not connected or when a mail account is configured
to use SMTP delivery. Your credentials are stored encrypted.
{smtpLoading ? (
Loading SMTP settings…
) : (
)}
{/* Account Information */}
Account Information
Subscription tier:
{displayUser?.subscription_tier ?? '—'}
Subscription status:
{displayUser?.subscription_status ?? '—'}
Member since:
{displayUser?.created_at
? new Date(displayUser.created_at).toLocaleDateString(undefined, {
year: 'numeric',
month: 'long',
day: 'numeric',
})
: '—'}
{displayUser?.oauth_provider && (
Linked account:
{displayUser.oauth_provider}
)}
{displayUser?.last_login_at && (
Last login:
{new Date(displayUser.last_login_at).toLocaleString()}
)}
{/* Security Section */}
Security
Password change and two-factor authentication settings are coming soon.
{displayUser?.oauth_provider === 'google' && (
Your account is authenticated via Google OAuth — password management is handled by Google.
)}
);
}