import { useState, type FormEvent } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { Alert, Box, Button, Card, CardContent, IconButton, InputAdornment, Stack, TextField, Typography, useTheme } from '@mui/material';
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import { ApiError } from '@/api/client';
import { Logo } from '@/components/Logo';
import { useUi } from '@/i18n/useUi';
import { useAuth } from '@/providers/AuthProvider';
import { LoginHero } from './LoginHero';
import { ThemeToggle } from './Toggles';
/** Pre-login page: uses ONLY the built-in ui table (no server captions exist before sign-in). */
export function LoginPage() {
const { t } = useUi();
const theme = useTheme();
const { status, login } = useAuth();
const location = useLocation();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [show, setShow] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
if (status === 'authed') {
const from = (location.state as { from?: string } | null)?.from;
return ;
}
async function submit(e: FormEvent) {
e.preventDefault();
if (!username.trim() || !password) { setError(t('login.required')); return; }
setBusy(true);
setError('');
try {
await login(username.trim(), password);
} catch (err) {
// backend message verbatim; our own text only when there is none
setError(err instanceof ApiError && err.status !== 0 && err.message ? err.message : err instanceof ApiError ? err.message : t('login.failed'));
} finally {
setBusy(false);
}
}
return (
// the brand panel (first child) sits on the physical right in both directions (the RTL style plugin would flip a "direction" rule)
{/* on wide screens the logo is in the brand panel */}
{t('login.heroTitle')}
{t('login.subtitle')}
{error && {error}}
setUsername(e.target.value)}
autoComplete="username" autoFocus required slotProps={{ htmlInput: { dir: 'ltr', style: { textAlign: 'start' } } }}
/>
setPassword(e.target.value)}
type={show ? 'text' : 'password'} autoComplete="current-password" required
slotProps={{
htmlInput: { dir: 'ltr' },
input: {
endAdornment: (
setShow((s) => !s)} aria-label={show ? t('login.hidePassword') : t('login.showPassword')}>
{show ? : }
),
},
}}
/>
{t('login.copyright')} - {new Date().getFullYear()}
);
}