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

export default function LoginPage({ onForgotPassword }) {
  const { login } = useAuth();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  async function handleSubmit(event) {
    event.preventDefault();
    setError(null);
    setIsSubmitting(true);
    const result = await login(username, password);
    setIsSubmitting(false);
    if (!result.success) {
      let message = "Benutzername oder Passwort falsch.";
      if (result.error === "network_error") {
        message = "Server nicht erreichbar. Bitte Verbindung prüfen und erneut versuchen.";
      } else if (result.error === "too_many_attempts") {
        message = "Zu viele Fehlversuche. Bitte in einigen Minuten erneut versuchen.";
      }
      setError(message);
    }
  }

  return (
    <div className="login-screen">
      <OmsorgCard>
        <h2>
          Anmelden bei
          <span className="accent"> Omsorg Business Controls Pro</span>
        </h2>

        <form onSubmit={handleSubmit} className="login-form">
          <label>
            Benutzername
            <input
              type="text"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              autoFocus
              required
            />
          </label>

          <label>
            Passwort
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
          </label>

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

          <OmsorgButton type="submit" icon={LogIn} disabled={isSubmitting}>
            {isSubmitting ? "Anmelden..." : "Anmelden"}
          </OmsorgButton>

          <div className="login-form-links">
            <button type="button" onClick={onForgotPassword}>
              Passwort vergessen?
            </button>
          </div>
        </form>
      </OmsorgCard>
    </div>
  );
}
