import { FormEvent, useState } from "react";
import { Sparkles } from "lucide-react";
import { api } from "../api/client";
import { navigate } from "../router";
import { ErrorRibbon, Panel } from "../components/ui";

export function SetupPage() {
  const [email, setEmail] = useState("admin@readabook.local");
  const [name, setName] = useState("Conservateur");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string>();

  async function submit(event: FormEvent) {
    event.preventDefault();
    setError(undefined);
    try {
      await api.bootstrap({ email, name, password });
      navigate("/login");
    } catch (setupError) {
      setError(setupError instanceof Error ? setupError.message : "Initialisation impossible");
    }
  }

  return (
    <div className="auth-surface">
      <section className="auth-hero">
        <p>Premiere cle</p>
        <h1>Installer le cabinet</h1>
        <span>Un administrateur, puis les rayonnages.</span>
      </section>
      <Panel className="auth-panel">
        <Sparkles size={24} />
        <h2>Premier administrateur</h2>
        <ErrorRibbon message={error} />
        <form onSubmit={submit} className="stack-form">
          <label>
            Nom
            <input value={name} onChange={(event) => setName(event.target.value)} required />
          </label>
          <label>
            Email
            <input value={email} onChange={(event) => setEmail(event.target.value)} type="email" required />
          </label>
          <label>
            Mot de passe
            <input value={password} onChange={(event) => setPassword(event.target.value)} type="password" minLength={8} required />
          </label>
          <button className="primary-button" type="submit">
            Creer la cle
          </button>
        </form>
      </Panel>
    </div>
  );
}
