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

const API_BASE = import.meta.env.VITE_API_BASE_URL || "http://localhost:8080/api";
const TOKEN_KEY = "br_kummerkasten_access_token";

function emptySubmission() {
  return {
    title: "",
    submitter_name: "",
    submitter_contact: "",
    description: "",
  };
}

async function publicRequest(path, options = {}) {
  const response = await fetch(`${API_BASE}${path}`, {
    ...options,
    headers: {
      ...(options.body ? { "Content-Type": "application/json" } : {}),
      ...(options.headers || {}),
    },
    credentials: "include",
  });

  const data = await response.json().catch(() => ({}));

  if (!response.ok) {
    const err = new Error(data.error || "Anfrage konnte nicht verarbeitet werden.");
    err.status = response.status;
    throw err;
  }

  return data;
}

export default function KummerkastenPage() {
  const [status, setStatus] = useState({ enabled: false, password_required: true, intro_text: "" });
  const [accessToken, setAccessToken] = useState(() => sessionStorage.getItem(TOKEN_KEY) || "");
  const [password, setPassword] = useState("");
  const [form, setForm] = useState(() => emptySubmission());
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);

  async function loadStatus() {
    setLoading(true);
    setError("");
    try {
      const data = await publicRequest("/public/kummerkasten/status");
      setStatus(data || {});
    } catch (err) {
      setError(err.message || "Der Kummerkasten-Status konnte nicht geladen werden.");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    loadStatus();
  }, []);

  const hasAccess = useMemo(() => Boolean(accessToken), [accessToken]);

  function updateField(field, value) {
    setForm((prev) => ({ ...prev, [field]: value }));
  }

  async function unlock(event) {
    event.preventDefault();
    setError("");
    setMessage("");

    if (String(password || "").trim().length < 4) {
      setError("Das Kennwort muss mindestens 4 Zeichen lang sein.");
      return;
    }

    try {
      const data = await publicRequest("/public/kummerkasten/access", {
        method: "POST",
        body: JSON.stringify({ password }),
      });
      const token = data.accessToken || "";
      sessionStorage.setItem(TOKEN_KEY, token);
      setAccessToken(token);
      setPassword("");
      setMessage("Kummerkasten freigeschaltet. Sie können jetzt einen TOP-Vorschlag einreichen.");
    } catch (err) {
      setError(err.message || "Kennwort konnte nicht geprüft werden.");
    }
  }

  async function submit(event) {
    event.preventDefault();
    setError("");
    setMessage("");
    setSubmitting(true);
    try {
      const payload = {
        public_access_token: accessToken,
        title: form.title.trim(),
        description: form.description.trim(),
        submitter_name: form.submitter_name.trim() || null,
        submitter_contact: form.submitter_contact.trim() || null,
      };

      const result = await publicRequest("/public/kummerkasten/submit", {
        method: "POST",
        body: JSON.stringify(payload),
      });

      setMessage(`Vielen Dank. Ihr Anliegen wurde als TOP-Bestandseintrag #${result.agenda_item_id} angelegt.`);
      setForm(emptySubmission());
    } catch (err) {
      if (err.status === 401) {
        sessionStorage.removeItem(TOKEN_KEY);
        setAccessToken("");
      }
      setError(err.message || "Einreichung konnte nicht gespeichert werden.");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <>
      <style>{`
        .public-kummer-page {
          min-height: 100vh;
          background: radial-gradient(circle at top left, rgba(37, 99, 235, 0.16), transparent 32%), #f6f8fb;
          padding: 32px 16px;
          color: #0f172a;
        }

        .public-kummer-shell {
          width: min(900px, 100%);
          margin: 0 auto;
          display: grid;
          gap: 18px;
        }

        .public-kummer-card {
          background: #ffffff;
          border: 1px solid rgba(148, 164, 184, 0.24);
          border-radius: 24px;
          box-shadow: 0 24px 80px rgba(15, 23, 42, 0.12);
          overflow: hidden;
        }

        .public-kummer-header {
          padding: 28px 30px 22px;
          border-bottom: 1px solid rgba(148, 164, 184, 0.22);
          background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
        }

        .public-kummer-header h1 {
          margin: 0;
          font-size: clamp(1.6rem, 3vw, 2.35rem);
        }

        .public-kummer-header p {
          margin: 10px 0 0;
          color: #64748b;
          line-height: 1.55;
        }

        .public-kummer-body {
          padding: 26px 30px 30px;
          display: grid;
          gap: 16px;
        }

        .public-kummer-form {
          display: grid;
          gap: 14px;
        }

        .public-kummer-grid {
          display: grid;
          grid-template-columns: repeat(2, minmax(0, 1fr));
          gap: 12px;
        }

        .public-kummer-label {
          display: grid;
          gap: 6px;
          font-weight: 700;
        }

        .public-kummer-label span small {
          color: #64748b;
          font-weight: 500;
        }

        .public-kummer-input,
        .public-kummer-textarea {
          width: 100%;
          box-sizing: border-box;
          border: 1px solid rgba(148, 164, 184, 0.55);
          border-radius: 14px;
          padding: 12px 13px;
          font: inherit;
          background: #ffffff;
          color: #0f172a;
        }

        .public-kummer-textarea {
          min-height: 180px;
          resize: vertical;
        }

        .public-kummer-actions {
          display: flex;
          justify-content: flex-end;
          gap: 10px;
          flex-wrap: wrap;
        }

        .public-kummer-btn {
          border: 0;
          border-radius: 999px;
          padding: 12px 18px;
          font-weight: 800;
          cursor: pointer;
          background: #2563eb;
          color: #ffffff;
          box-shadow: 0 10px 24px rgba(37, 99, 235, 0.22);
        }

        .public-kummer-btn:disabled {
          opacity: 0.65;
          cursor: wait;
        }

        .public-kummer-alert {
          border-radius: 16px;
          padding: 12px 14px;
          font-weight: 700;
        }

        .public-kummer-alert.error {
          background: #fef2f2;
          color: #991b1b;
          border: 1px solid #fecaca;
        }

        .public-kummer-alert.success {
          background: #ecfdf5;
          color: #065f46;
          border: 1px solid #bbf7d0;
        }

        .public-kummer-note {
          color: #64748b;
          line-height: 1.5;
          font-size: 0.95rem;
        }

        @media (max-width: 720px) {
          .public-kummer-page { padding: 16px 10px; }
          .public-kummer-header, .public-kummer-body { padding-left: 18px; padding-right: 18px; }
          .public-kummer-grid { grid-template-columns: 1fr; }
          .public-kummer-actions { justify-content: stretch; }
          .public-kummer-btn { width: 100%; }
        }
      `}</style>

      <main className="public-kummer-page">
        <div className="public-kummer-shell">
          <section className="public-kummer-card">
            <div className="public-kummer-header">
              <h1>Kummerkasten</h1>
              <p>
                {status.intro_text || "Reichen Sie hier einen Vorschlag oder ein Anliegen für die Tagesordnung ein."}
                {status.target_committee_name ? ` Ziel-Gremium: ${status.target_committee_name}.` : ""}
              </p>
            </div>

            <div className="public-kummer-body">
              {loading ? <div className="public-kummer-note">Lade Kummerkasten…</div> : null}
              {error ? <div className="public-kummer-alert error">{error}</div> : null}
              {message ? <div className="public-kummer-alert success">{message}</div> : null}

              {!loading && !status.enabled ? (
                <div className="public-kummer-alert error">Der Kummerkasten ist derzeit nicht freigeschaltet.</div>
              ) : null}

              {!loading && status.enabled && !hasAccess ? (
                <form className="public-kummer-form" onSubmit={unlock}>
                  <label className="public-kummer-label">
                    <span>Globales Kennwort</span>
                    <input
                      className="public-kummer-input"
                      type="password"
                      autoComplete="current-password"
                      value={password}
                      onChange={(event) => setPassword(event.target.value)}
                      required
                      minLength={4}
                    />
                  </label>
                  <p className="public-kummer-note">Das Kennwort muss mindestens 4 Zeichen lang sein.</p>
                  <div className="public-kummer-actions">
                    <button className="public-kummer-btn" type="submit">Kummerkasten öffnen</button>
                  </div>
                </form>
              ) : null}

              {!loading && status.enabled && hasAccess ? (
                <form className="public-kummer-form" onSubmit={submit}>
                  <label className="public-kummer-label">
                    <span>Titel</span>
                    <input
                      className="public-kummer-input"
                      value={form.title}
                      onChange={(event) => updateField("title", event.target.value)}
                      required
                      minLength={3}
                      maxLength={220}
                      placeholder="Kurzer Titel für den TOP"
                    />
                  </label>

                  <label className="public-kummer-label">
                    <span>Name <small>(optional)</small></span>
                    <input
                      className="public-kummer-input"
                      value={form.submitter_name}
                      onChange={(event) => updateField("submitter_name", event.target.value)}
                      maxLength={255}
                      placeholder="Ihr Name oder anonym lassen"
                    />
                  </label>

                  <label className="public-kummer-label">
                    <span>Kontaktmöglichkeit <small>(optional)</small></span>
                    <input
                      className="public-kummer-input"
                      value={form.submitter_contact}
                      onChange={(event) => updateField("submitter_contact", event.target.value)}
                      maxLength={255}
                      placeholder="E-Mail, Telefon oder leer lassen"
                    />
                  </label>

                  <label className="public-kummer-label">
                    <span>Beschreibung</span>
                    <textarea
                      className="public-kummer-textarea"
                      value={form.description}
                      onChange={(event) => updateField("description", event.target.value)}
                      required
                      minLength={3}
                      maxLength={8000}
                      placeholder="Beschreiben Sie das Anliegen möglichst konkret. Daraus wird ein TOP-Bestandseintrag erzeugt."
                    />
                  </label>

                  <p className="public-kummer-note">
                    Nach dem Absenden wird automatisch ein neuer Eintrag im TOP-Bestand angelegt. Die spätere Zuordnung zu einer Sitzung erfolgt intern.
                  </p>

                  <div className="public-kummer-actions">
                    <button className="public-kummer-btn" type="submit" disabled={submitting}>
                      {submitting ? "Wird eingereicht…" : "Als TOP einreichen"}
                    </button>
                  </div>
                </form>
              ) : null}
            </div>
          </section>
        </div>
      </main>
    </>
  );
}
