"use client";

import { FormEvent, useEffect, useState } from "react";

type SalesContact = { name: string; phone: string; email: string; url: string; note: string };

const EMPTY: SalesContact = { name: "", phone: "", email: "", url: "", note: "" };

// Entered once here, shown to every restaurant in Podešavanja > Kontakt
// prodaje. A client on the basic tier should never have to hunt for who to call
// in order to unlock the rest.
export default function SalesContactEditor() {
  const [form, setForm] = useState<SalesContact>(EMPTY);
  const [loaded, setLoaded] = useState(false);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let active = true;
    fetch("/api/sales-contact", { cache: "no-store", credentials: "same-origin" })
      .then((response) => response.json())
      .then((payload) => {
        if (!active) return;
        if (payload?.ok) setForm({ ...EMPTY, ...(payload.contact as SalesContact) });
        setLoaded(true);
      })
      .catch(() => { if (active) setLoaded(true); });
    return () => { active = false; };
  }, []);

  async function submit(event: FormEvent) {
    event.preventDefault();
    setSaving(true);
    setSaved(false);
    setError(null);
    const response = await fetch("/api/sales-contact", {
      method: "POST",
      credentials: "same-origin",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(form),
    });
    const payload = await response.json().catch(() => null);
    setSaving(false);
    if (!response.ok || !payload?.ok) {
      setError(payload?.error?.message ?? "Kontakt nije sačuvan.");
      return;
    }
    setForm({ ...EMPTY, ...(payload.contact as SalesContact) });
    setSaved(true);
  }

  if (!loaded) return null;

  return <section className="library-manager">
    <header>
      <h2>Kontakt prodaje MeniFlow</h2>
      <p>
        Ovo vide svi restorani u svom admin panelu, u Podešavanja &gt; Kontakt
        prodaje. Ostavite prazno ono što ne želite da prikažete.
      </p>
    </header>
    <form className="platform-details" onSubmit={submit}>
      <label>Kontakt osoba
        <input value={form.name} maxLength={100} placeholder="npr. Prodaja MeniFlow"
          onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))} />
      </label>
      <label>Telefon
        <input value={form.phone} maxLength={30} placeholder="060 123 4567"
          onChange={(event) => setForm((current) => ({ ...current, phone: event.target.value }))} />
      </label>
      <label>Email
        <input type="email" value={form.email} maxLength={160} placeholder="prodaja@meniflow.rs"
          onChange={(event) => setForm((current) => ({ ...current, email: event.target.value }))} />
      </label>
      <label>Sajt ili link
        <input value={form.url} maxLength={200} placeholder="https://meniflow.rs/cenovnik"
          onChange={(event) => setForm((current) => ({ ...current, url: event.target.value }))} />
      </label>
      <label className="wide">Poruka klijentu
        <input value={form.note} maxLength={300} placeholder="Radnim danima 09–17h. Pitajte za paket za više lokacija."
          onChange={(event) => setForm((current) => ({ ...current, note: event.target.value }))} />
      </label>
      <div className="platform-add-actions">
        <button className="primary-button" type="submit" disabled={saving}>
          {saving ? "Čuvamo…" : "Sačuvaj kontakt"}
        </button>
        {saved && <span className="platform-ok">Sačuvano.</span>}
      </div>
      {error && <div className="auth-error" role="alert">{error}</div>}
    </form>
  </section>;
}
