"use client";

import { FormEvent, useState } from "react";

export default function RegisterForm() {
  const [displayName, setDisplayName] = useState("");
  const [restaurantName, setRestaurantName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [currency, setCurrency] = useState("RSD");
  const [mobile, setMobile] = useState("");
  const [phone, setPhone] = useState("");
  const [address, setAddress] = useState("");
  const [city, setCity] = useState("");
  const [postalCode, setPostalCode] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [working, setWorking] = useState(false);

  async function submit(event: FormEvent) {
    event.preventDefault();
    setWorking(true);
    setError(null);
    try {
      const response = await fetch("/api/auth/register", {
        method: "POST",
        credentials: "same-origin",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          displayName, restaurantName, email, password, currency,
          mobile, phone, address, city, postalCode,
        }),
      });
      const payload = await response.json().catch(() => null);
      if (!response.ok || !payload?.ok) {
        setError(payload?.error?.message ?? "Registracija nije uspela. Pokušajte ponovo.");
        setWorking(false);
        return;
      }
      window.location.assign(payload.redirect ?? "/admin");
    } catch {
      setError("Server trenutno nije dostupan. Pokušajte ponovo.");
      setWorking(false);
    }
  }

  return (
    <form className="login-card" onSubmit={submit}>
      <div className="platform-mark">M</div>
      <p className="eyebrow">Portal za restorane</p>
      <h2>Napravite nalog</h2>
      <p>
        Dobijate svoj restoran, prvi sto i QR kod odmah, i <strong>30 dana sve
        opcije bez ograničenja</strong>. Bez kartice. Posle probnog perioda
        ostaje poziv konobaru dok ne aktivirate pretplatu.
      </p>
      <label>Vaše ime i prezime
        <input value={displayName} maxLength={100} required autoComplete="name"
          onChange={(event) => setDisplayName(event.target.value)} placeholder="npr. Marko Marković" />
      </label>
      <label>Naziv restorana
        <input value={restaurantName} maxLength={80} required
          onChange={(event) => setRestaurantName(event.target.value)} placeholder="npr. Kod Mice" />
      </label>
      <label>Email adresa
        <input type="email" value={email} maxLength={160} required autoComplete="email"
          onChange={(event) => setEmail(event.target.value)} placeholder="vi@restoran.rs" />
      </label>
      <label>Lozinka
        <input type="password" value={password} minLength={12} maxLength={200} required
          autoComplete="new-password" onChange={(event) => setPassword(event.target.value)}
          placeholder="Najmanje 12 znakova" />
        <small>Najmanje 12 znakova, bar jedno slovo i jedan broj.</small>
      </label>
      <label>Valuta
        <select value={currency} onChange={(event) => setCurrency(event.target.value)}>
          <option value="RSD">RSD — dinar</option>
          <option value="EUR">EUR — evro</option>
        </select>
      </label>
      <label>Vaš mobilni telefon <i>(opciono)</i>
        <input value={mobile} maxLength={30} autoComplete="tel"
          onChange={(event) => setMobile(event.target.value)} placeholder="064 123 4567" />
      </label>
      <label>Telefon restorana <i>(opciono)</i>
        <input value={phone} maxLength={30}
          onChange={(event) => setPhone(event.target.value)} placeholder="011 234 5678" />
      </label>
      <label>Adresa restorana <i>(opciono)</i>
        <input value={address} maxLength={160} autoComplete="street-address"
          onChange={(event) => setAddress(event.target.value)} placeholder="Cara Dušana 12" />
      </label>
      <label>Grad <i>(opciono)</i>
        <input value={city} maxLength={80}
          onChange={(event) => setCity(event.target.value)} placeholder="Beograd" />
      </label>
      <label>Poštanski broj <i>(opciono)</i>
        <input value={postalCode} maxLength={20} inputMode="numeric"
          onChange={(event) => setPostalCode(event.target.value)} placeholder="11000" />
        <small>Kontakt podatke koristimo samo za podršku i račun. Možete ih dodati i kasnije.</small>
      </label>
      {error && <div className="auth-error" role="alert">{error}</div>}
      <button className="primary-button wide" type="submit" disabled={working}>
        {working ? "Pravimo nalog…" : "Napravi nalog"} <span>→</span>
      </button>
      <div className="demo-note">
        <span>Već imate nalog?</span> <a href="/login">Prijavite se</a>.
      </div>
    </form>
  );
}
