import { useState } from "react";
import { KeyRound } from "lucide-react";
import OmsorgCard from "../../components/OmsorgCard";
import OmsorgButton from "../../components/ui/OmsorgButton";
import { useAuth } from "../../app/AuthContext";

export default function ForgotPasswordNewPasswordPage({ resetToken, onDone, onBackToLogin }) {
  const { passwordMinLength } = useAuth();
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [error, setError] = useState(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  async function handleSubmit(event) {
    event.preventDefault();
    setError(null);

    if (password.length < passwordMinLength) {
      setError(`Das neue Passwort muss mindestens ${passwordMinLength} Zeichen lang sein.`);
      return;
    }

    if (password !== confirmPassword) {
      setError("Die Passwörter stimmen nicht überein.");
      return;
    }

    setIsSubmitting(true);
    const result = await window.omsorg.auth.resetPassword(resetToken, password);
    setIsSubmitting(false);

    if (result.success) {
      onDone();
    } else if (result.error === "password_too_short") {
      setError(result.message || `Das neue Passwort muss mindestens ${passwordMinLength} Zeichen lang sein.`);
    } else {
      setError("Der Code ist abgelaufen. Bitte fordere einen neuen an.");
    }
  }

  return (
    <div className="login-screen">
      <OmsorgCard>
        <h2>
          Neues
          <span className="accent"> Passwort setzen</span>
        </h2>

        <form onSubmit={handleSubmit} className="login-form">
          <label>
            Neues Passwort
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              autoFocus
              required
            />
          </label>

          <label>
            Passwort bestätigen
            <input
              type="password"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              required
            />
          </label>

          {error && <p className="login-error">{error}</p>}

          <OmsorgButton type="submit" icon={KeyRound} disabled={isSubmitting}>
            {isSubmitting ? "Wird gespeichert..." : "Passwort speichern"}
          </OmsorgButton>

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