import { useEffect, useState } from "react";

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

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

function dateOnly(value) {
  if (!value) return "";
  return new Intl.DateTimeFormat("de-DE", { dateStyle: "medium" }).format(new Date(value));
}

function publicDocumentUrl(id, mode = "view", token = "") {
  const query = token ? `?access_token=${encodeURIComponent(token)}` : "";
  return `${API_BASE}/public/documents/${id}/${mode}${query}`;
}

export default function PublicDocumentsPage() {
  const [status, setStatus] = useState({ enabled: false, authenticated: false, intro_text: "", documents: [] });
  const [accessToken, setAccessToken] = useState(() => sessionStorage.getItem(TOKEN_STORAGE_KEY) || "");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [message, setMessage] = useState("");
  const [loading, setLoading] = useState(true);
  const [unlocking, setUnlocking] = useState(false);

  async function loadStatus(token = accessToken) {
    setLoading(true);
    setError("");
    try {
      const query = token ? `?access_token=${encodeURIComponent(token)}` : "";
      const data = await publicRequest(`/public/documents/status${query}`);
      setStatus(data || {});
      if (token && data?.enabled && !data?.authenticated) {
        sessionStorage.removeItem(TOKEN_STORAGE_KEY);
        setAccessToken("");
      }
    } catch (err) {
      setError(err.message || "Die öffentliche Dokumentenseite konnte nicht geladen werden.");
    } finally {
      setLoading(false);
    }
  }

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

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

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

    setUnlocking(true);
    try {
      const data = await publicRequest("/public/documents/access", {
        method: "POST",
        body: JSON.stringify({ password: trimmed }),
      });
      const token = data.accessToken || "";
      sessionStorage.setItem(TOKEN_STORAGE_KEY, token);
      setAccessToken(token);
      setPassword("");
      setMessage("Zugriff freigeschaltet.");
      await loadStatus(token);
    } catch (err) {
      setError(err.message || "Kennwort konnte nicht geprüft werden.");
    } finally {
      setUnlocking(false);
    }
  }

  function lockAgain() {
    sessionStorage.removeItem(TOKEN_STORAGE_KEY);
    setAccessToken("");
    setPassword("");
    setMessage("Zugriff wurde gesperrt.");
    loadStatus("");
  }

  const authenticated = Boolean(status.enabled && status.authenticated && accessToken);

  return (
    <>
      <style>{`
        .public-doc-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-doc-shell { width: min(980px, 100%); margin: 0 auto; display: grid; gap: 18px; }
        .public-doc-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-doc-header { padding: 28px 30px 22px; border-bottom: 1px solid rgba(148, 164, 184, 0.22); background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%); }
        .public-doc-header h1 { margin: 0; font-size: clamp(1.6rem, 3vw, 2.35rem); }
        .public-doc-header p { margin: 10px 0 0; color: #64748b; line-height: 1.55; white-space: pre-wrap; }
        .public-doc-body { padding: 26px 30px 30px; display: grid; gap: 14px; }
        .public-doc-item { border: 1px solid rgba(148, 164, 184, 0.28); border-radius: 18px; padding: 16px; display: grid; gap: 10px; background: #ffffff; }
        .public-doc-item h2 { margin: 0; font-size: 1.1rem; }
        .public-doc-meta { color: #64748b; font-size: .92rem; display: flex; gap: 8px; flex-wrap: wrap; }
        .public-doc-description { color: #334155; line-height: 1.5; white-space: pre-wrap; margin: 0; }
        .public-doc-actions { display: flex; gap: 8px; flex-wrap: wrap; }
        .public-doc-btn { display: inline-flex; align-items: center; justify-content: center; border: 0; border-radius: 999px; padding: 10px 14px; font-weight: 800; text-decoration: none; background: #2563eb; color: #ffffff; cursor: pointer; }
        .public-doc-btn.secondary { background: #e2e8f0; color: #0f172a; }
        .public-doc-alert { border-radius: 16px; padding: 12px 14px; font-weight: 700; }
        .public-doc-alert.error { background: #fef2f2; color: #991b1b; border: 1px solid #fecaca; }
        .public-doc-alert.success { background: #ecfdf5; color: #065f46; border: 1px solid #bbf7d0; }
        .public-doc-note { color: #64748b; line-height: 1.5; }
        .public-doc-access { border: 1px solid rgba(37, 99, 235, .18); background: #f8fbff; border-radius: 18px; padding: 18px; display: grid; gap: 12px; }
        .public-doc-access h2 { margin: 0; font-size: 1.15rem; }
        .public-doc-form { display: grid; gap: 10px; max-width: 420px; }
        .public-doc-form label { display: grid; gap: 6px; font-weight: 700; }
        .public-doc-input { width: 100%; border: 1px solid rgba(148, 164, 184, .5); border-radius: 14px; padding: 11px 12px; font: inherit; }
      `}</style>

      <div className="public-doc-page">
        <div className="public-doc-shell">
          <div className="public-doc-card">
            <div className="public-doc-header">
              <h1>Öffentliche Dokumente</h1>
              <p>{status.intro_text || "Vom Betriebsrat freigegebene Dokumente"}</p>
            </div>
            <div className="public-doc-body">
              {error ? <div className="public-doc-alert error">{error}</div> : null}
              {message ? <div className="public-doc-alert success">{message}</div> : null}
              {loading ? <p className="public-doc-note">Dokumente werden geladen …</p> : null}

              {!loading && !status.enabled ? (
                <p className="public-doc-note">Die öffentliche Dokumentenseite ist derzeit nicht freigeschaltet.</p>
              ) : null}

              {!loading && status.enabled && !authenticated ? (
                <div className="public-doc-access">
                  <h2>Kennwort erforderlich</h2>
                  <p className="public-doc-note">
                    Diese Seite ist nicht frei öffentlich. Bitte geben Sie das bekannte Kennwort ein, um die freigegebenen Dokumente anzuzeigen.
                  </p>
                  <form className="public-doc-form" onSubmit={unlock}>
                    <label>
                      <span>Kennwort</span>
                      <input
                        className="public-doc-input"
                        type="password"
                        minLength="4"
                        value={password}
                        onChange={(event) => setPassword(event.target.value)}
                        autoComplete="current-password"
                      />
                    </label>
                    <button className="public-doc-btn" type="submit" disabled={unlocking}>
                      {unlocking ? "Prüfe…" : "Dokumente anzeigen"}
                    </button>
                  </form>
                </div>
              ) : null}

              {!loading && authenticated && !(status.documents || []).length ? (
                <p className="public-doc-note">Derzeit sind keine öffentlichen Dokumente verfügbar.</p>
              ) : null}

              {authenticated ? (
                <div className="public-doc-actions">
                  <button className="public-doc-btn secondary" type="button" onClick={lockAgain}>Zugriff sperren</button>
                </div>
              ) : null}

              {authenticated ? (status.documents || []).map((doc) => (
                <article className="public-doc-item" key={doc.id}>
                  <div>
                    <h2>{doc.title}</h2>
                    <div className="public-doc-meta">
                      <span>{doc.document_number}</span>
                      {doc.category_label ? <span>· {doc.category_label}</span> : null}
                      {doc.file_name ? <span>· {doc.file_name}</span> : null}
                      {doc.uploaded_at ? <span>· {dateOnly(doc.uploaded_at)}</span> : null}
                    </div>
                  </div>
                  {doc.description ? <p className="public-doc-description">{doc.description}</p> : null}
                  <div className="public-doc-actions">
                    <a className="public-doc-btn" href={publicDocumentUrl(doc.id, "view", accessToken)} target="_blank" rel="noreferrer">Dokument öffnen</a>
                    <a className="public-doc-btn secondary" href={publicDocumentUrl(doc.id, "download", accessToken)}>Download</a>
                  </div>
                </article>
              )) : null}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
