import { useState } from "react";
import { api } from "../lib/api";
import type { AppConfig } from "../types";

export default function Login({ config, onSignedIn }: {
  config: AppConfig | null; onSignedIn: () => void;
}) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setBusy(true); setError("");
    try {
      await api.post("/api/auth/login", { email, password });
      onSignedIn();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Sign-in failed");
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="card login">
      <h2 style={{ marginTop: 0 }}>{config?.app_name ?? "CX Triage"}</h2>

      {config?.oidc_enabled && (
        <>
          <a className="navlink" style={{ display: "block", textAlign: "center", padding: 10 }}
             href="/api/auth/oidc/start">Sign in with SSO</a>
          {config.local_login && <div className="hint" style={{ textAlign: "center" }}>or use a local account</div>}
        </>
      )}

      {config?.local_login !== false && (
        <form onSubmit={submit} style={{ marginTop: 14 }}>
          <div className="fld">
            <label>Email</label>
            <input value={email} onChange={(e) => setEmail(e.target.value)} autoComplete="username" />
          </div>
          <div className="fld">
            <label>Password</label>
            <input type="password" value={password} onChange={(e) => setPassword(e.target.value)}
                   autoComplete="current-password" />
          </div>
          {error && <div className="warnbox t-bad">{error}</div>}
          <button className="pri" style={{ width: "100%" }} disabled={busy}>
            {busy ? "Signing in…" : "Sign in"}
          </button>
        </form>
      )}
    </div>
  );
}
