import { useState } from 'react';
import { Link } from 'react-router-dom';
import { useForgotPassword } from '../api/queries.js';

export default function ForgotPassword() {
  const forgotPassword = useForgotPassword();
  const [email, setEmail] = useState('');
  const [sent, setSent] = useState(false);
  const [error, setError] = useState('');

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    try {
      await forgotPassword.mutateAsync(email);
      setSent(true);
    } catch (err) {
      setError(err.message);
    }
  }

  return (
    <div className="auth-page">
      <h1>Przypomnij hasło</h1>
      {sent ? (
        <p>Jeśli konto z tym adresem e-mail istnieje, wysłaliśmy wiadomość z linkiem do resetu hasła.</p>
      ) : (
        <>
          <p className="auth-subtitle">Podaj e-mail, na który wyślemy link do zresetowania hasła</p>
          <form onSubmit={handleSubmit} className="auth-form">
            <input
              type="email"
              placeholder="E-mail"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
            />
            {error && <p className="form-error">{error}</p>}
            <button type="submit" className="btn-primary" disabled={forgotPassword.isPending}>
              {forgotPassword.isPending ? 'Wysyłanie…' : 'Wyślij link'}
            </button>
          </form>
        </>
      )}
      <p>
        <Link to="/login">Powrót do logowania</Link>
      </p>
    </div>
  );
}
