import { useState, type FormEvent } from "react";
import { Link, useNavigate } from "react-router-dom";
import { register } from "../api/client";
import type { Ruolo } from "../types";

export default function Register() {
  const navigate = useNavigate();
  const [form, setForm] = useState({
    nome: "",
    cognome: "",
    email: "",
    password: "",
    confermaPassword: "",
    ruolo: "DIPENDENTE" as Ruolo,
  });
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setError(null);
    setSuccess(null);
    setLoading(true);
    try {
      await register(form);
      setSuccess("Registrazione completata. Ora puoi accedere.");
      setTimeout(() => navigate("/login"), 1500);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Errore di registrazione");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="auth-page">
      <form className="auth-card" onSubmit={handleSubmit}>
        <h1>Registrati</h1>
        {error && <p className="error">{error}</p>}
        {success && <p className="success">{success}</p>}
        <label>
          Nome
          <input value={form.nome} onChange={(e) => setForm({ ...form, nome: e.target.value })} required />
        </label>
        <label>
          Cognome
          <input value={form.cognome} onChange={(e) => setForm({ ...form, cognome: e.target.value })} required />
        </label>
        <label>
          Email
          <input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} required />
        </label>
        <label>
          Password
          <input type="password" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} required />
        </label>
        <label>
          Conferma password
          <input type="password" value={form.confermaPassword} onChange={(e) => setForm({ ...form, confermaPassword: e.target.value })} required />
        </label>
        <label>
          Ruolo
          <select value={form.ruolo} onChange={(e) => setForm({ ...form, ruolo: e.target.value as Ruolo })}>
            <option value="DIPENDENTE">Dipendente</option>
            <option value="RESPONSABILE_AMMINISTRATIVO">Responsabile amministrativo</option>
          </select>
        </label>
        <button type="submit" className="btn btn-primary" disabled={loading}>
          {loading ? "Registrazione..." : "Registrati"}
        </button>
        <p className="auth-link">
          Hai già un account? <Link to="/login">Accedi</Link>
        </p>
      </form>
    </div>
  );
}
