// frontend/src/components/Register.jsx
import React, { useState } from 'react';
import axios from 'axios';

export default function Register({ toggleView }) {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [message, setMessage] = useState({ text: '', isError: false });

  const handleRegister = async (e) => {
    e.preventDefault();
    setMessage({ text: '', isError: false });

    // Validate password match before hitting the API
    if (password !== confirmPassword) {
      return setMessage({ text: 'Passwords do not match.', isError: true });
    }

    try {
      const res = await axios.post('http://localhost:5000/api/auth/register', { 
        username, 
        password 
      });
      
      setMessage({ 
        text: res.data.message + ' Redirecting to login...', 
        isError: false 
      });
      
      // Automatically toggle back to login screen after 2 seconds
      setTimeout(() => {
        toggleView();
      }, 2000);
      
    } catch (err) {
      const errorMsg = err.response?.data?.error || 'Registration failed.';
      setMessage({ text: errorMsg, isError: true });
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-slate-950 px-4">
      <div className="w-full max-w-md bg-white/5 backdrop-blur-lg rounded-2xl border border-white/10 p-8 shadow-2xl">
        <h2 className="text-3xl font-extrabold text-white text-center mb-2">Create Account</h2>
        <p className="text-center text-slate-400 text-sm mb-8">Add new staff credentials to RRBMS</p>
        
        {message.text && (
          <div className={`mb-4 p-3 rounded-lg text-sm border transition-all ${
            message.isError 
              ? 'bg-rose-500/20 border-rose-500/30 text-rose-300' 
              : 'bg-emerald-500/20 border-emerald-500/30 text-emerald-300'
          }`}>
            {message.text}
          </div>
        )}
        
        <form onSubmit={handleRegister} className="space-y-5">
          <div>
            <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">
              Username
            </label>
            <input 
              type="text" 
              value={username} 
              onChange={e => setUsername(e.target.value)} 
              className="w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-amber-500 transition" 
              placeholder="e.g., waiter_admin" 
              required 
            />
          </div>
          
          <div>
            <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">
              Password
            </label>
            <input 
              type="password" 
              value={password} 
              onChange={e => setPassword(e.target.value)} 
              className="w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-amber-500 transition" 
              placeholder="••••••••" 
              required 
            />
          </div>
          
          <div>
            <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">
              Confirm Password
            </label>
            <input 
              type="password" 
              value={confirmPassword} 
              onChange={e => setConfirmPassword(e.target.value)} 
              className="w-full bg-slate-900 border border-white/10 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-amber-500 transition" 
              placeholder="••••••••" 
              required 
            />
          </div>
          
          <button 
            type="submit" 
            className="w-full bg-amber-500 hover:bg-amber-600 text-slate-950 font-bold py-3 px-4 rounded-xl transition shadow-lg shadow-amber-500/20"
          >
            Register Staff Member
          </button>
        </form>

        <div className="mt-6 text-center">
          <button 
            onClick={toggleView} 
            className="text-sm text-amber-400 hover:underline transition bg-transparent border-none cursor-pointer"
          >
            Already have an account? Log In
          </button>
        </div>
      </div>
    </div>
  );
}