import React, { useState } from 'react';
import { requestPasswordReset, resetPassword } from '../../services/passwordReset';
import './PasswordReset.css';

function PasswordReset() {
  const [step, setStep] = useState('request'); // 'request' or 'reset'
  const [username, setUsername] = useState('');
  const [token, setToken] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState({ type: '', text: '' });

  const handleRequestReset = async (e) => {
    e.preventDefault();
    setLoading(true);
    setMessage({ type: '', text: '' });

    const result = await requestPasswordReset(username);
    
    setLoading(false);
    
    if (result.success) {
      setMessage({ type: 'success', text: result.message });
      if (result.token) {
        // Development mode - token returned directly
        setToken(result.token);
      }
      setStep('reset');
    } else {
      setMessage({ type: 'error', text: result.message });
    }
  };

  const handleResetPassword = async (e) => {
    e.preventDefault();
    setMessage({ type: '', text: '' });

    // Validation
    if (newPassword.length < 6) {
      setMessage({ type: 'error', text: 'Passwort muss mindestens 6 Zeichen lang sein' });
      return;
    }

    if (newPassword !== confirmPassword) {
      setMessage({ type: 'error', text: 'Passwörter stimmen nicht überein' });
      return;
    }

    setLoading(true);

    const result = await resetPassword(token, newPassword);
    
    setLoading(false);
    
    if (result.success) {
      setMessage({ type: 'success', text: result.message + ' - Sie können sich jetzt anmelden.' });
      // Reset form
      setTimeout(() => {
        setStep('request');
        setUsername('');
        setToken('');
        setNewPassword('');
        setConfirmPassword('');
        window.location.href = '/'; // Redirect to login
      }, 2000);
    } else {
      setMessage({ type: 'error', text: result.message });
    }
  };

  return (
    <div className="password-reset-container">
      <div className="password-reset-card">
        <h2>Passwort zurücksetzen</h2>
        
        {message.text && (
          <div className={`message ${message.type}`}>
            {message.text}
          </div>
        )}

        {step === 'request' ? (
          <form onSubmit={handleRequestReset}>
            <div className="form-group">
              <label htmlFor="username">Benutzername</label>
              <input
                type="text"
                id="username"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                required
                disabled={loading}
                placeholder="Ihr Benutzername"
              />
            </div>

            <button type="submit" disabled={loading} className="btn-primary">
              {loading ? 'Wird bearbeitet...' : 'Reset-Token anfordern'}
            </button>

            <div className="form-footer">
              <a href="/">Zurück zum Login</a>
            </div>
          </form>
        ) : (
          <form onSubmit={handleResetPassword}>
            <div className="form-group">
              <label htmlFor="token">Reset-Token</label>
              <input
                type="text"
                id="token"
                value={token}
                onChange={(e) => setToken(e.target.value)}
                required
                disabled={loading}
                placeholder="Token aus E-Mail oder Log"
              />
              <small>Der Token wurde Ihnen per E-Mail zugeschickt (oder im Log in Dev-Modus)</small>
            </div>

            <div className="form-group">
              <label htmlFor="newPassword">Neues Passwort</label>
              <input
                type="password"
                id="newPassword"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                required
                disabled={loading}
                placeholder="Mindestens 6 Zeichen"
                minLength={6}
              />
            </div>

            <div className="form-group">
              <label htmlFor="confirmPassword">Passwort bestätigen</label>
              <input
                type="password"
                id="confirmPassword"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                required
                disabled={loading}
                placeholder="Passwort wiederholen"
                minLength={6}
              />
            </div>

            <button type="submit" disabled={loading} className="btn-primary">
              {loading ? 'Wird gespeichert...' : 'Passwort zurücksetzen'}
            </button>

            <div className="form-footer">
              <button 
                type="button" 
                onClick={() => setStep('request')}
                className="btn-link"
              >
                Neuen Token anfordern
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

export default PasswordReset;
