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('La contraseña debe tener al menos 8 caracteres');
      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' ? 'No se pudo crear la cuenta' : 'Inicio de sesión fallido'));
      } else {
        onLogin(data.user);
      }
    } catch {
      setError('Error de red — inténtalo de nuevo');
    } 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}
          >
            Iniciar sesión
          </button>
          <button
            type="button"
            role="tab"
            aria-selected={isRegister}
            className={`modal-tab${isRegister ? ' is-active' : ''}`}
            onClick={() => setMode('register')}
            disabled={loading}
          >
            Crear cuenta
          </button>
        </div>

        <h2 id="modal-title">{isRegister ? 'Crea tu cuenta' : 'Bienvenido de nuevo'}</h2>
        <p className="modal-sub">
          {isRegister
            ? 'Guarda tu dirección y recibe notificaciones cuando lleguen medicamentos.'
            : 'Inicia sesión para gestionar tu perfil y notificaciones.'}
        </p>

        <form onSubmit={handleSubmit} noValidate>
          <div className="modal-field">
            <label htmlFor="modal-username">Usuario</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 caracteres: letras, dígitos o guión bajo.</p>
            )}
          </div>
          <div className="modal-field">
            <label htmlFor="modal-password">Contraseña</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">Al menos 8 caracteres.</p>
            )}
          </div>
          {error && <p className="modal-error">{error}</p>}
          <div className="modal-actions">
            <button
              type="button"
              className="modal-cancel"
              onClick={onClose}
              disabled={loading}
            >
              Cancelar
            </button>
            <button
              type="submit"
              className="modal-submit"
              disabled={loading || !username.trim() || !password}
            >
              {loading
                ? (isRegister ? 'Creando…' : 'Iniciando sesión…')
                : (isRegister ? 'Crear cuenta' : 'Iniciar sesión')}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

export default LoginModal;
