"use client";

import { useState, type FormEvent } from "react";
import { Icon } from "@/components/Icon";
import { api, ensureCsrf } from "@/lib/client";

interface PostItem {
  id: number;
  body: string;
  created_at: string;
  author_name: string;
  author_username: string;
}

export function SocialBoard({
  initialPosts,
  unread,
  canPublish,
  locale,
}: {
  initialPosts: PostItem[];
  unread: number;
  canPublish: boolean;
  locale: "ar" | "en";
}) {
  const isAr = locale === "ar";
  const [posts, setPosts] = useState(initialPosts);
  const [message, setMessage] = useState<{ kind: "ok" | "err"; text: string } | null>(null);
  const [busy, setBusy] = useState(false);
  const ar = isAr;

  async function publish(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const f = new FormData(e.currentTarget);
    const body = String(f.get("body") ?? "").trim();
    if (body.length < 3) return;
    setBusy(true);
    setMessage(null);
    const csrf = await ensureCsrf();
    const res = await fetch("/api/social/posts", {
      method: "POST",
      headers: { "content-type": "application/json", "x-csrf-token": csrf ?? "" },
      body: JSON.stringify({ body }),
      credentials: "same-origin",
    });
    setBusy(false);
    if (res.ok) {
      setMessage({ kind: "ok", text: ar ? "تم النشر" : "Published" });
      (e.target as HTMLFormElement).reset();
      const feed = await fetch("/api/social/posts", { credentials: "same-origin" });
      if (feed.ok) setPosts((await feed.json()).items ?? []);
    } else {
      const b = await res.json().catch(() => ({}));
      setMessage({ kind: "err", text: b.error ?? (ar ? "تعذر النشر" : "Publish failed") });
    }
  }

  async function remove(id: number) {
    const reason = window.prompt(ar ? "سبب الإزالة (موثق في التدقيق):" : "Removal reason (audited):");
    if (!reason || reason.trim().length < 3) return;
    const csrf = await ensureCsrf();
    setBusy(true);
    const res = await fetch(`/api/social/posts/${id}/remove`, {
      method: "POST",
      headers: { "content-type": "application/json", "x-csrf-token": csrf ?? "" },
      body: JSON.stringify({ reason }),
      credentials: "same-origin",
    });
    setBusy(false);
    if (res.ok) {
      setPosts((p) => p.filter((x) => x.id !== id));
    }
  }

  return (
    <div className="space-y-6">
      <header>
        <h1 className="text-2xl font-extrabold text-slate-900">{ar ? "الشبكة الاجتماعية" : "Social network"}</h1>
        {unread > 0 && (
          <p className="mt-2 rounded-lg border border-bousla-200 bg-bousla-50 px-4 py-2 text-sm font-semibold text-bousla-800">
            {ar ? `لديك ${unread} تنبيهًا غير مقروء` : `You have ${unread} unread notifications`}
          </p>
        )}
      </header>

      {message && (
        <div role="status" className={`rounded-lg border px-4 py-2.5 text-sm ${message.kind === "ok" ? "border-emerald-200 bg-emerald-50 text-emerald-800" : "border-red-200 bg-red-50 text-red-700"}`}>
          {message.text}
        </div>
      )}

      {canPublish && (
        <form onSubmit={publish} className="rounded-xl border border-slate-200 bg-white p-5 shadow-card">
          <textarea
            name="body"
            required
            minLength={3}
            maxLength={4000}
            rows={3}
            dir="auto"
            placeholder={ar ? "شارك خبرًا أو توجيهًا للأعضاء…" : "Share news or guidance with members…"}
            className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100"
          />
          <div className="mt-3 flex justify-end">
            <button type="submit" disabled={busy} className="rounded-lg bg-bousla-700 px-4 py-2 text-sm font-bold text-white hover:bg-bousla-800 disabled:opacity-60">
              {ar ? "نشر" : "Publish"}
            </button>
          </div>
        </form>
      )}

      <section className="rounded-xl border border-slate-200 bg-white p-5 shadow-card">
        <h2 className="mb-4 font-bold text-slate-900">{ar ? "المنشورات" : "Posts"}</h2>
        {posts.length === 0 ? (
          <p className="text-sm text-slate-400">{ar ? "لا منشورات بعد" : "No posts yet"}</p>
        ) : (
          <ul className="space-y-3">
            {posts.map((p) => (
              <li key={p.id} className="rounded-lg border border-slate-100 bg-slate-50/60 px-4 py-3">
                <div className="flex items-center justify-between gap-2">
                  <span className="text-xs font-bold text-slate-500" dir="auto">{p.author_name}</span>
                  <div className="flex items-center gap-2">
                    <span className="text-[11px] text-slate-400">{p.created_at.slice(0, 16).replace("T", " ")}</span>
                    {canPublish && (
                      <button onClick={() => void remove(p.id)} disabled={busy} title={ar ? "إزالة (موثقة)" : "Remove (audited)"} className="text-xs font-bold text-red-600 hover:underline disabled:opacity-50">
                        {ar ? "إزالة" : "Remove"}
                      </button>
                    )}
                  </div>
                </div>
                <p className="mt-2 whitespace-pre-wrap text-sm leading-6 text-slate-700" dir="auto">{p.body}</p>
              </li>
            ))}
          </ul>
        )}
      </section>
    </div>
  );
}
