import { useState } from "react";
import { ShieldCheck } from "lucide-react";
import OmsorgCard from "../../components/OmsorgCard";
import OmsorgButton from "../../components/ui/OmsorgButton";

export default function ForgotPasswordPinPage({ username, onVerified, onRestart, onBackToLogin }) {
  const [pin, setPin] = useState("");
  const [error, setError] = useState(null);
  const [tooManyAttempts, setTooManyAttempts] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  async function handleSubmit(event) {
    event.preventDefault();
    setError(null);
    setTooManyAttempts(false);
    setIsSubmitting(true);
    const result = await window.omsorg.auth.verifyPasswordResetCode(username, pin);
    setIsSubmitting(false);

    if (result.success) {
      onVerified(result.resetToken);
      return;
    }

    if (result.error === "too_many_attempts") {
      setTooManyAttempts(true);
    } else {
      setError("Code falsch oder abgelaufen.");
    }
  }

  return (
    <div className="login-screen">
      <OmsorgCard>
        <h2>
          Code
          <span className="accent"> eingeben</span>
        </h2>
        <p className="login-info">
          Wir haben einen 6-stelligen Code an die hinterlegte E-Mail-Adresse gesendet. Der Code ist 5 Minuten gültig.
        </p>

        <form onSubmit={handleSubmit} className="login-form">
          <label>
            Code
            <input
              type="text"
              inputMode="numeric"
              pattern="[0-9]*"
              maxLength={6}
              value={pin}
              onChange={(e) => setPin(e.target.value.replace(/\D/g, ""))}
              autoFocus
              required
            />
          </label>

          {error && <p className="login-error">{error}</p>}
          {tooManyAttempts && (
            <p className="login-error">
              Zu viele Fehlversuche. Bitte fordere einen neuen Code an.
            </p>
          )}

          <OmsorgButton type="submit" icon={ShieldCheck} disabled={isSubmitting || tooManyAttempts}>
            {isSubmitting ? "Wird geprüft..." : "Bestätigen"}
          </OmsorgButton>

          <div className="login-form-links">
            <button type="button" onClick={onRestart}>
              Neuen Code anfordern
            </button>
            <button type="button" onClick={onBackToLogin}>
              Zurück zum Login
            </button>
          </div>
        </form>
      </OmsorgCard>
    </div>
  );
}
