import React, { useState, useEffect, useRef } from 'react';
import './LoginModal.css';

function LoginModal({ onLogin, onClose, initialMode = 'login' }) {
  const [mode, setMode] = useState(initialMode === 'register' ? 'register' : 'login');
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const usernameRef = useRef(null);

  useEffect(() => {
    usernameRef.current?.focus();
    function handleKey(e) { if (e.key === 'Escape') onClose(); }
    document.addEventListener('keydown', handleKey);
    return () => document.removeEventListener('keydown', handleKey);
  }, [onClose]);

  useEffect(() => {
    setError('');
  }, [mode]);

  async function handleSubmit(e) {
    e.preventDefault();
    const u = username.trim();
    if (!u || !password) return;
    if (mode === 'register' && password.length < 8) {
      setError('Password must be at least 8 characters');
      return;
    }
    setLoading(true);
    setError('');
    try {
      const endpoint = mode === 'register' ? '/api/auth/register' : '/api/auth/login';
      const res = await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ username: u, password }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setError(data.error || (mode === 'register' ? 'Could not create account' : 'Login failed'));
      } else {
        onLogin(data.user);
      }
    } catch {
      setError('Network error — try again');
    } finally {
      setLoading(false);
    }
  }

  const isRegister = mode === 'register';

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div
        className="modal-box"
        onClick={e => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-labelledby="modal-title"
      >
        <div className="modal-tabs" role="tablist">
          <button
            type="button"
            role="tab"
            aria-selected={!isRegister}
            className={`modal-tab${!isRegister ? ' is-active' : ''}`}
            onClick={() => setMode('login')}
            disabled={loading}
          >
            Sign in
          </button>
          <button
            type="button"
            role="tab"
            aria-selected={isRegister}
            className={`modal-tab${isRegister ? ' is-active' : ''}`}
            onClick={() => setMode('register')}
            disabled={loading}
          >
            Create account
          </button>
        </div>

        <h2 id="modal-title">{isRegister ? 'Create your account' : 'Welcome back'}</h2>
        <p className="modal-sub">
          {isRegister
            ? 'Save your address and get notified when medicines arrive.'
            : 'Sign in to manage your profile and notifications.'}
        </p>

        <form onSubmit={handleSubmit} noValidate>
          <div className="modal-field">
            <label htmlFor="modal-username">Username</label>
            <input
              id="modal-username"
              type="text"
              value={username}
              onChange={e => setUsername(e.target.value)}
              autoComplete="username"
              ref={usernameRef}
              disabled={loading}
              minLength={isRegister ? 3 : undefined}
              maxLength={isRegister ? 32 : undefined}
            />
            {isRegister && (
              <p className="modal-hint">3–32 characters: letters, digits, or underscore.</p>
            )}
          </div>
          <div className="modal-field">
            <label htmlFor="modal-password">Password</label>
            <input
              id="modal-password"
              type="password"
              value={password}
              onChange={e => setPassword(e.target.value)}
              autoComplete={isRegister ? 'new-password' : 'current-password'}
              disabled={loading}
              minLength={isRegister ? 8 : undefined}
            />
            {isRegister && (
              <p className="modal-hint">At least 8 characters.</p>
            )}
          </div>
          {error && <p className="modal-error">{error}</p>}
          <div className="modal-actions">
            <button
              type="button"
              className="modal-cancel"
              onClick={onClose}
              disabled={loading}
            >
              Cancel
            </button>
            <button
              type="submit"
              className="modal-submit"
              disabled={loading || !username.trim() || !password}
            >
              {loading
                ? (isRegister ? 'Creating…' : 'Signing in…')
                : (isRegister ? 'Create account' : 'Sign in')}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

export default LoginModal;
