import Link from "next/link";
import { notFound } from "next/navigation";
import { hidePostAction, replyToPostAction, startThreadForm } from "@/app/actions/community";
import { Portrait } from "@/components/cards";
import { prisma } from "@/lib/prisma";
import { isAdmin, profileTypeLabel } from "@/lib/roles";
import { readSession } from "@/lib/session";

const KIND_LABEL: Record<string, string> = {
  discussion: "Question",
  update: "Update",
  announcement: "Notice",
  event: "Event",
};

function formatWhen(date: Date) {
  return date.toLocaleString(undefined, {
    month: "short",
    day: "numeric",
    hour: "numeric",
    minute: "2-digit",
  });
}

export default async function ThreadPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ error?: string }>;
}) {
  const { id } = await params;
  const { error } = await searchParams;
  const session = await readSession();

  const post = await prisma.post.findUnique({
    where: { id },
    include: {
      author: { include: { profile: true } },
      replies: {
        include: { author: { include: { profile: true } } },
        orderBy: { createdAt: "asc" },
      },
    },
  });
  if (!post || post.hidden) notFound();

  const place = [post.author.profile?.company, post.author.profile?.location, post.author.profile?.country]
    .filter(Boolean)
    .join(" · ");

  return (
    <div className="page page--wide">
      <div className="thread-wrap">
      <p className="profile-back">
        <Link href="/feed">← Floor</Link>
      </p>

      <div className="thread">
        <div className="thread-board">
          <article className="thread-op">
            <div className="thread-op__who">
              <Portrait name={post.author.name} src={post.author.profile?.photoUrl} size="md" />
              <div>
                <Link href={`/members/${post.authorId}`}>{post.author.name}</Link>
                <p>
                  {profileTypeLabel(post.author.profile?.type || "collector")}
                  {place ? ` · ${place}` : ""}
                </p>
              </div>
              <div className="thread-op__tags">
                <span className={`kind-pill kind-pill--${post.kind}`}>
                  {KIND_LABEL[post.kind] || post.kind}
                </span>
                <time>{formatWhen(post.createdAt)}</time>
              </div>
            </div>
            <h1>{post.title}</h1>
            {post.eventAt ? (
              <p className="thread-event">
                {formatWhen(post.eventAt)}
                {post.location ? ` · ${post.location}` : ""}
              </p>
            ) : null}
            <p className="thread-body">{post.body}</p>
          </article>

          <p className="thread-split">
            {post.replies.length} {post.replies.length === 1 ? "reply" : "replies"}
          </p>

          {post.replies.length === 0 ? (
            <p className="thread-empty">No replies yet.</p>
          ) : (
            <div className="thread-list">
              {post.replies.map((reply) => (
                <article key={reply.id} className="thread-reply">
                  <Portrait name={reply.author.name} src={reply.author.profile?.photoUrl} size="sm" />
                  <div>
                    <div className="thread-reply__who">
                      <Link href={`/members/${reply.authorId}`}>{reply.author.name}</Link>
                      {reply.author.profile?.type ? (
                        <span>{profileTypeLabel(reply.author.profile.type)}</span>
                      ) : null}
                      <time>{formatWhen(reply.createdAt)}</time>
                    </div>
                    <p>{reply.body}</p>
                  </div>
                </article>
              ))}
            </div>
          )}

          <div className="thread-compose">
            {session ? (
              <form action={replyToPostAction.bind(null, post.id)}>
                <p className="eg-eyebrow">Reply</p>
                {error === "1" ? <p className="composer__error">Write a short reply.</p> : null}
                <textarea
                  id="body"
                  name="body"
                  rows={3}
                  placeholder="Answer, add a source, or ask a follow-up"
                  required
                />
                <button className="eg-btn eg-btn-solid" type="submit">
                  Post reply
                </button>
              </form>
            ) : (
              <p className="text-sm text-muted">
                <Link href={`/login?next=/feed/${post.id}`} className="text-primary">
                  Sign in
                </Link>{" "}
                to reply on this thread.
              </p>
            )}
          </div>
        </div>

        <aside className="thread__aside">
          <div className="thread-side">
            <p className="eg-eyebrow">Author</p>
            <Link href={`/members/${post.authorId}`} className="thread-person">
              <Portrait name={post.author.name} src={post.author.profile?.photoUrl} size="md" />
              <span>
                <strong>{post.author.name}</strong>
                <small>{profileTypeLabel(post.author.profile?.type || "collector")}</small>
              </span>
            </Link>
            {session && session.id !== post.authorId ? (
              <form action={startThreadForm.bind(null, post.authorId)}>
                <button className="eg-btn eg-btn-outline" type="submit">
                  Open a deal room
                </button>
              </form>
            ) : (
              <Link href={`/members/${post.authorId}`} className="eg-btn eg-btn-outline">
                View profile
              </Link>
            )}
            <p className="thread-aside__note">Public thread. Private parcels stay in rooms.</p>
            {isAdmin(session) ? (
              <form action={hidePostAction.bind(null, post.id)}>
                <button className="floor-hide" type="submit">
                  Hide thread
                </button>
              </form>
            ) : null}
          </div>
        </aside>
      </div>
      </div>
    </div>
  );
}
