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

function Register() {
  const navigate = useNavigate();
  const [name, setName] = useState('');
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    try {
      const response = await axios.post('http://localhost:5001/api/auth/register', { name, username, password });
      localStorage.setItem('token', response.data.token);
      localStorage.setItem('user', JSON.stringify(response.data.user));
      navigate('/dashboard');
    } catch (err) {
      setError(err.response?.data?.message || 'Registration failed');
      console.error(err.response?.data || err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen items-center justify-center px-4">
      <div className="lms-card w-full max-w-md p-8 shadow-lg">
        <p className="text-xs font-semibold uppercase tracking-wider text-slate-400">Library LMS</p>
        <h1 className="mt-1 mb-6 text-2xl font-semibold text-white">Register staff</h1>

        {error && <p className="lms-alert-error">{error}</p>}

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="lms-label">Name</label>
            <input
              type="text"
              required
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="lms-input"
            />
          </div>

          <div>
            <label className="lms-label">Username</label>
            <input
              type="text"
              required
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              className="lms-input"
            />
          </div>

          <div>
            <label className="lms-label">Password</label>
            <input
              type="password"
              required
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="lms-input"
            />
          </div>

          <button type="submit" disabled={loading} className="lms-btn-primary w-full">
            {loading ? 'Creating account...' : 'Create account'}
          </button>
        </form>

        <p className="mt-4 text-center text-xs text-slate-500">After registering you will be taken to the dashboard.</p>
        <p className="mt-2 text-center text-xs">
          Already have an account? <Link to="/login" className="text-blue-400 underline">Sign in</Link>
        </p>
      </div>
    </div>
  );
}

export default Register;
