 import { useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from 'axios';

function Register () {
    const [username, setUsername] = useState(''); // Fixed variable name to match form
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const navigate = useNavigate();

    const handleRegister = async (e) => {
        e.preventDefault();
        setError('');
        try {
            const res = await axios.post('http://localhost:5000/api/user/register', {
                username, 
                password
            });
            navigate("/login");
        } catch(error) {
            setError("Failed to register. Username might be taken.");
        }
    };

    return(
        <div className="min-h-screen bg-slate-100 flex items-center justify-center p-4">
            <div className="bg-white p-8 rounded shadow-md w-full max-w-md flex flex-col gap-4">
                
                <h2 className="text-2xl font-bold text-slate-700 text-center">REGISTER</h2>
                
                {error && (
                    <p className="text-red-500 bg-red-100 p-2 rounded text-sm text-center font-semibold">{error}</p>
                )}

                <form onSubmit={handleRegister} className="flex flex-col gap-4">
                    
                    <div className="flex flex-col gap-1">
                        <label className="text-sm font-semibold text-slate-600">Username</label>
                        <input 
                            type="text" 
                            placeholder="Choose a username"
                            required 
                            className="border border-slate-300 p-2 rounded focus:outline-none focus:border-blue-500"
                            onChange={(e) => setUsername(e.target.value)} 
                        />
                    </div>

                    <div className="flex flex-col gap-1">
                        <label className="text-sm font-semibold text-slate-600">Password</label>
                        <input 
                            type="password" 
                            placeholder="Create a password"
                            required 
                            className="border border-slate-300 p-2 rounded focus:outline-none focus:border-blue-500"
                            onChange={(e) => setPassword(e.target.value)} 
                        />
                    </div>

                    <button 
                        type="submit" 
                        className="bg-green-500 text-white font-bold p-2 rounded mt-2 hover:bg-green-600 transition"
                    >
                        Register
                    </button>
                    
                </form>
            </div>
        </div>
    );
}

export default Register;
