'use client' import { useState, useEffect } from 'react' import { useRouter, useSearchParams } from 'next/navigation' interface Props { isFirstRun: boolean } export default function LoginForm({ isFirstRun }: Props) { const router = useRouter() const searchParams = useSearchParams() const [username, setUsername] = useState('') const [password, setPassword] = useState('') const [confirmPassword, setConfirmPassword] = useState('') const [error, setError] = useState('') const [loading, setLoading] = useState(false) const from = searchParams.get('from') ?? '/' async function handleSubmit(e: React.FormEvent) { e.preventDefault() setError('') if (isFirstRun && password !== confirmPassword) { setError('Passwords do not match') return } setLoading(true) try { if (isFirstRun) { const res = await fetch('/api/auth/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password, role: 'admin' }), }) if (!res.ok) { const data = await res.json() setError(data.error ?? 'Registration failed') return } } const loginRes = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }), }) if (!loginRes.ok) { const data = await loginRes.json() setError(data.error ?? 'Login failed') return } router.push(from) router.refresh() } finally { setLoading(false) } } return (
{isFirstRun ? 'Create your admin account to get started' : 'Sign in to your account'}