import { useState } from "react";
import { useNavigate } from "react-router-dom";
import api from "../services/api";

function RegisterPage() {
    const navigate = useNavigate();
    const [form, setForm] = useState({ username: "", password: "", fullName: "" });
    const [error, setError] = useState("");

    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            await api.post("/auth/register", form);
            // After registration, send user to login.
            navigate("/login");
        } catch (err) {
            setError(err.response?.data?.message || "Registration failed");
        }
    };

    return (
        <div className="flex min-h-screen items-center justify-center bg-gradient-to-br from-cyan-900 to-slate-950 px-4">
            <form onSubmit={handleSubmit} className="w-full max-w-md rounded-xl bg-white p-6 shadow-2xl">
                <h2 className="mb-4 text-2xl font-bold text-slate-800">CRPMS Register</h2>
                {error ? <p className="mb-3 text-sm text-red-600">{error}</p> : null}

                <input
                    className="mb-3 w-full rounded-md border px-3 py-2"
                    placeholder="Full Name"
                    value={form.fullName}
                    onChange={(e) => setForm({ ...form, fullName: e.target.value })}
                    required
                />
                <input
                    className="mb-3 w-full rounded-md border px-3 py-2"
                    placeholder="Username"
                    value={form.username}
                    onChange={(e) => setForm({ ...form, username: e.target.value })}
                    required
                />
                <input
                    className="mb-4 w-full rounded-md border px-3 py-2"
                    type="password"
                    placeholder="Password"
                    value={form.password}
                    onChange={(e) => setForm({ ...form, password: e.target.value })}
                    required
                />

                <button className="w-full rounded-md bg-cyan-700 px-4 py-2 font-semibold text-white hover:bg-cyan-800">
                    Register
                </button>

                <button
                    type="button"
                    onClick={() => navigate("/login")}
                    className="mt-3 w-full rounded-md bg-slate-200 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-300"
                >
                    Back to Login
                </button>
            </form>
        </div>
    );
}

export default RegisterPage;

