import { ZodStringSchema } from '@/lib/consts' import { zodResolver } from '@hookform/resolvers/zod' import { useForm } from 'react-hook-form' import * as z from 'zod' import { Form, FormControl, FormField, FormItem, FormMessage, FormLabel } from '@/components/ui/form' import { Input } from './ui/input' import { login } from '@/api/auth' import { Button } from './ui/button' import { ExclamationTriangleIcon } from '@radix-ui/react-icons' import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert' import { useState } from 'react' import { useToast } from './ui/use-toast' import { RespCode } from '@/lib/pb/common' import { useRouter } from 'next/router' import { useTranslation } from 'react-i18next'; export const LoginSchema = z.object({ username: ZodStringSchema, password: ZodStringSchema, }) export function LoginComponent() { const { t } = useTranslation(); const form = useForm>({ resolver: zodResolver(LoginSchema), }) const { toast } = useToast() const router = useRouter() const [loginAlert, setLoginAlert] = useState(false) const onSubmit = async (values: z.infer) => { toast({ title: t('auth.loggingIn') }) try { const res = await login({ ...values }) if (res.status?.code === RespCode.SUCCESS) { toast({ title: t('auth.loginSuccess') }) setTimeout(() => { router.push('/') }, 3000) setLoginAlert(false) } else { toast({ title: t('auth.loginFailed') }) setLoginAlert(true) } } catch (e) { toast({ title: t('auth.loginFailed') }) console.log('login error', e) setLoginAlert(true) } } return (
( {t('auth.usernamePlaceholder')} )} /> ( {t('auth.password')} )} /> {loginAlert && ( {t('auth.error')} {t('auth.loginFailed')} )}
) }