import { useEffect, useState } from 'react'; import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; import { useAuthStore } from '@/auth'; import { Button } from '@/ui/primitives/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/primitives/card'; import { Alert, AlertDescription } from '@/ui/primitives/alert'; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from '@/ui/primitives/form'; import { Input } from '@/ui/primitives/input'; const LoginFormSchema = z.object({ email: z.string().email({ message: 'Enter a valid email address.' }), password: z.string().min(1, { message: 'Password is required.' }), }); type LoginForm = z.infer; /** * Dev-only prefill from `VITE_ADMIN_EMAIL` / `VITE_ADMIN_PASSWORD`. * Production builds get empty strings regardless of build-time env values. */ const devDefaults = import.meta.env.DEV ? { email: import.meta.env.VITE_ADMIN_EMAIL ?? '', password: import.meta.env.VITE_ADMIN_PASSWORD ?? '', } : { email: '', password: '' }; export type LoginPageProps = { /** Called once the auth store transitions to `'authenticated'`. */ onAuthenticated?: () => void; }; export function LoginPage({ onAuthenticated }: LoginPageProps) { const status = useAuthStore((s) => s.status); const isSubmitting = status === 'authenticating'; const [submitError, setSubmitError] = useState(null); const form = useForm({ resolver: zodResolver(LoginFormSchema), defaultValues: devDefaults, }); // If the auth store flips to authenticated (e.g. login succeeds, or another // tab logs in concurrently), notify the surrounding container. useEffect(() => { if (status === 'authenticated') { onAuthenticated?.(); } }, [status, onAuthenticated]); async function onSubmit(values: LoginForm) { setSubmitError(null); const result = await useAuthStore.getState().login(values.email, values.password); if (!result.ok) { setSubmitError(result.error); } // Success path is handled by the status effect above. } return (
Sign in to TRM Use your operator credentials. {submitError && ( {submitError} )}
( Email )} /> ( Password )} />
); }