import React, { useState } from 'react';
import { handlerLogin, setHandlerPassword } from '../../services/handler';
import './HandlerLogin.css';

const HandlerLogin = ({ onLogin }) => {
  const [mode, setMode] = useState('login'); // 'login' | 'set-password'
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [newPassword2, setNewPassword2] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [loading, setLoading] = useState(false);

  const handleLogin = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const result = await handlerLogin(email, password);
      if (result.success) {
        localStorage.setItem('handlerToken', result.token);
        onLogin(result.user);
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Anmeldung fehlgeschlagen');
    } finally {
      setLoading(false);
    }
  };

  const handleSetPassword = async (e) => {
    e.preventDefault();
    setError('');
    if (newPassword !== newPassword2) {
      setError('Passwörter stimmen nicht überein');
      return;
    }
    if (newPassword.length < 6) {
      setError('Passwort muss mindestens 6 Zeichen haben');
      return;
    }
    setLoading(true);
    try {
      const result = await setHandlerPassword(email, newPassword);
      if (result.success) {
        setSuccess('Passwort erfolgreich gesetzt. Sie können sich nun anmelden.');
        setMode('login');
        setNewPassword('');
        setNewPassword2('');
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Fehler beim Setzen des Passworts');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="handler-login-container">
      <div className="handler-login-card">
        <h2>Hundeführer-Login</h2>
        <p className="handler-login-subtitle">
          Melden Sie sich an, um Ihre Verfügbarkeit und Kontaktdaten zu verwalten.
        </p>

        <div className="handler-mode-toggle">
          <button
            className={mode === 'login' ? 'active' : ''}
            onClick={() => { setMode('login'); setError(''); setSuccess(''); }}
          >
            Anmelden
          </button>
          <button
            className={mode === 'set-password' ? 'active' : ''}
            onClick={() => { setMode('set-password'); setError(''); setSuccess(''); }}
          >
            Passwort erstmalig setzen
          </button>
        </div>

        {error && <div className="handler-error">{error}</div>}
        {success && <div className="handler-success">{success}</div>}

        {mode === 'login' ? (
          <form onSubmit={handleLogin} className="handler-form">
            <div className="form-group">
              <label>E-Mail</label>
              <input type="email" value={email} onChange={e => setEmail(e.target.value)} required autoFocus />
            </div>
            <div className="form-group">
              <label>Passwort</label>
              <input type="password" value={password} onChange={e => setPassword(e.target.value)} required />
            </div>
            <button type="submit" className="btn-handler-primary" disabled={loading}>
              {loading ? 'Anmelden...' : 'Anmelden'}
            </button>
          </form>
        ) : (
          <form onSubmit={handleSetPassword} className="handler-form">
            <p className="handler-hint">
              Der Admin hat Ihre E-Mail-Adresse hinterlegt. Geben Sie hier Ihre E-Mail und ein neues Passwort ein.
            </p>
            <div className="form-group">
              <label>E-Mail</label>
              <input type="email" value={email} onChange={e => setEmail(e.target.value)} required autoFocus />
            </div>
            <div className="form-group">
              <label>Neues Passwort (min. 6 Zeichen)</label>
              <input type="password" value={newPassword} onChange={e => setNewPassword(e.target.value)} required minLength={6} />
            </div>
            <div className="form-group">
              <label>Passwort wiederholen</label>
              <input type="password" value={newPassword2} onChange={e => setNewPassword2(e.target.value)} required />
            </div>
            <button type="submit" className="btn-handler-primary" disabled={loading}>
              {loading ? 'Wird gesetzt...' : 'Passwort setzen'}
            </button>
          </form>
        )}
      </div>
    </div>
  );
};

export default HandlerLogin;
