import React, { useState } from 'react';
import axios from 'axios';

function Login({ onLoginSuccess, API_URL }) {
  const [isRegisterMode, setIsRegisterMode] = useState(false);
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [notification, setNotification] = useState({ message: '', isError: false });

  const handleSubmit = async (e) => {
    e.preventDefault();
    setNotification({ message: '', isError: false });

    if (isRegisterMode) {
      try {
        const res = await axios.post(`${API_URL}/register`, { username, password });
        setNotification({ message: res.data.message + ' Switch to Login to continue.', isError: false });
        setUsername(''); setPassword('');
      } catch (err) {
        setNotification({ message: err.response?.data?.message || 'Registration processing error.', isError: true });
      }
    } else {
      try {
        const res = await axios.post(`${API_URL}/login`, { username, password });
        if (res.data.loggedIn) onLoginSuccess();
      } catch (err) {
        setNotification({ message: err.response?.data?.message || 'Verification failed.', isError: true });
      }
    }
  };

  return (
    <div className="flex items-center justify-center min-h-screen p-4">
      <div className="glass-panel w-full max-w-md p-8 rounded-2xl shadow-2xl">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-extrabold tracking-tight text-white mb-2">
            {isRegisterMode ? 'Create Account' : 'Welcome Back'}
          </h1>
          <p className="text-sm text-slate-400">Taste of Rwanda Reservation & Billing Management System</p>
        </div>

        {notification.message && (
          <div className={`mb-4 p-3 border rounded-xl text-sm text-center ${
            notification.isError ? 'bg-rose-500/20 border-rose-500/30 text-rose-400' : 'bg-emerald-500/20 border-emerald-500/30 text-emerald-400'
          }`}>
            {notification.message}
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-5">
          <div>
            <label className="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Username</label>
            <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} className="w-full bg-slate-950/50 border border-slate-800 rounded-xl px-4 py-3 text-slate-200 focus:outline-none focus:border-amber-500" required />
          </div>
          <div>
            <label className="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Password</label>
            <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} className="w-full bg-slate-950/50 border border-slate-800 rounded-xl px-4 py-3 text-slate-200 focus:outline-none focus:border-amber-500" required />
          </div>
          <button type="submit" className="w-full bg-gradient-to-r from-amber-500 to-orange-600 text-white font-semibold py-3 rounded-xl shadow-lg">
            {isRegisterMode ? 'Register Admin' : 'Login'}
          </button>
        </form>

        <div className="mt-6 text-center text-sm">
          <button onClick={() => { setIsRegisterMode(!isRegisterMode); setNotification({ message: '', isError: false }); }} className="text-amber-400 font-semibold hover:underline bg-transparent border-none">
            {isRegisterMode ? 'Already have an account? Login' : 'Need an operator profile? Register'}
          </button>
        </div>
      </div>
    </div>
  );
}

export default Login;