'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';

export default function Register() {
	const [name, setName] = useState('');
	const [email, setEmail] = useState('');
	const [password, setPassword] = useState('');
	const [message, setMessage] = useState('');
	const router = useRouter();

	const handleSubmit = async (e: React.FormEvent) => {
		e.preventDefault();
		try {
			const res = await fetch('http://localhost:8080/api/users/register', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
				},
				body: JSON.stringify({ name, email, password }),
			});

			if (res.ok) {
				localStorage.setItem('name', name);
				localStorage.setItem('email', email);
				router.push('/login');
			} else {
				setMessage('Error registering user');
			}
		} catch (error) {
			console.error('Error:', error);
			setMessage('Failed to connect to the server');
		}
	};

	return (
		<div className='flex flex-col items-center justify-center min-h-screen bg-purple-100'>
			<div className='bg-white p-8 rounded-lg shadow-md w-full max-w-md'>
				<h1 className='text-2xl font-bold mb-6 text-purple-700'>Register</h1>
				<form onSubmit={handleSubmit}>
					<div className='mb-4'>
						<label className='block text-purple-700 mb-2' htmlFor='name'>
							Name
						</label>
						<input
							className='w-full p-2 border border-purple-300 rounded text-purple-700'
							type='text'
							id='name'
							name='name'
							value={name}
							onChange={(e) => setName(e.target.value)}
							required
						/>
					</div>
					<div className='mb-4'>
						<label className='block text-purple-700 mb-2' htmlFor='email'>
							Email
						</label>
						<input
							className='w-full p-2 border border-purple-300 rounded text-purple-700'
							type='email'
							id='email'
							name='email'
							value={email}
							onChange={(e) => setEmail(e.target.value)}
							required
						/>
					</div>
					<div className='mb-6'>
						<label className='block text-purple-700 mb-2' htmlFor='password'>
							Password
						</label>
						<input
							className='w-full p-2 border border-purple-300 rounded text-purple-700'
							type='password'
							id='password'
							name='password'
							value={password}
							onChange={(e) => setPassword(e.target.value)}
							required
						/>
					</div>
					<button
						className='w-full bg-purple-700 text-white p-2 rounded hover:bg-purple-800'
						type='submit'
					>
						Register
					</button>
				</form>
				{message && <p className='mt-4 text-purple-700'>{message}</p>}
				<p className='mt-4 text-purple-700'>
					Already have an account?{' '}
					<Link href='/login' legacyBehavior>
						<a className='text-purple-500 hover:underline'>Login</a>
					</Link>
				</p>
			</div>
		</div>
	);
}
