import Link from "next/link";
import { notFound } from "next/navigation";
import { followAction, startThreadForm, unfollowAction } from "@/app/actions/community";
import { ListingCard, Portrait } from "@/components/cards";
import { gemTypeLabel } from "@/lib/listings";
import { prisma } from "@/lib/prisma";
import { isMemberVerified, isWholesale, profileTypeLabel } from "@/lib/roles";
import { readSession } from "@/lib/session";

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

export default async function MemberPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const session = await readSession();
  const member = await prisma.user.findUnique({
    where: { id },
    include: {
      profile: true,
      posts: { where: { hidden: false }, orderBy: { createdAt: "desc" }, take: 8 },
      listings: { orderBy: { createdAt: "desc" }, take: 8 },
      _count: { select: { followers: true, follows: true } },
    },
  });
  if (!member) notFound();

  const following = session
    ? await prisma.follow.findUnique({
        where: { followerId_followingId: { followerId: session.id, followingId: member.id } },
      })
    : null;

  const wholesale =
    member.wholesaleStatus === "approved" || member.role === "wholesale" || member.role === "admin";
  const verified = isMemberVerified(member);
  const craft = profileTypeLabel(member.profile?.type || "collector");
  const place = [member.profile?.location, member.profile?.country].filter(Boolean).join(" · ");
  const specs = (member.profile?.specialties || "")
    .split(",")
    .map((item) => item.trim())
    .filter(Boolean)
    .slice(0, 6);
  const listings = member.listings.filter((listing) => !listing.wholesaleOnly || isWholesale(session));
  const website = member.profile?.website?.trim();
  const facts = [
    ["Craft", craft],
    ["House", member.profile?.company],
    ["Based", place],
    ["Origin focus", member.profile?.originFocus],
    ["Years in trade", member.profile?.yearsInTrade],
    ["Labs", member.profile?.labs],
    ["Website", website],
  ].filter(([, value]) => Boolean(value));

  return (
    <div className="page page--wide">
      <div className="auction-wrap">
        <p className="profile-back">
          <Link href="/directory">← Members</Link>
          {member.profile?.company ? <span> · {member.profile.company}</span> : null}
        </p>

        <div className="auction member-file">
          <div className="auction-photo member-photo">
            <Portrait name={member.name} src={member.profile?.photoUrl} size="hero" />
            <span className="lot-card__status">{craft}</span>
            {wholesale ? <span className="lot-card__flag">Wholesale</span> : null}
          </div>

          <aside className="auction-desk">
            <p className="eg-eyebrow">{craft}</p>
            <h1>{member.name}</h1>
            {place ? <p className="auction-desk__lede">{place}</p> : null}

            <div className="profile-tags">
              {verified ? <span className="kind-pill kind-pill--discussion">Verified</span> : null}
              {member.featured ? <span className="kind-pill kind-pill--announcement">Featured</span> : null}
              {wholesale ? <span className="kind-pill">Trade desk</span> : null}
            </div>

            {member.profile?.bio ? <p className="profile-bio">{member.profile.bio}</p> : null}

            {specs.length ? (
              <div className="dir-card__specs profile-desk-specs">
                {specs.map((spec) => (
                  <span key={spec}>{spec}</span>
                ))}
              </div>
            ) : null}

            <dl className="auction-mini">
              <div>
                <dt>Followers</dt>
                <dd>{member._count.followers}</dd>
              </div>
              <div>
                <dt>Following</dt>
                <dd>{member._count.follows}</dd>
              </div>
              <div>
                <dt>Lots</dt>
                <dd>{listings.length}</dd>
              </div>
            </dl>

            <div className="member-desk__actions">
              {session && session.id !== member.id ? (
                <>
                  <form action={startThreadForm.bind(null, member.id)}>
                    <button className="eg-btn eg-btn-accent" type="submit">
                      Open a deal room
                    </button>
                  </form>
                  {following ? (
                    <form action={unfollowAction.bind(null, member.id)}>
                      <button className="eg-btn eg-btn-outline" type="submit">
                        Unfollow
                      </button>
                    </form>
                  ) : (
                    <form action={followAction.bind(null, member.id)}>
                      <button className="eg-btn eg-btn-outline" type="submit">
                        Follow
                      </button>
                    </form>
                  )}
                </>
              ) : null}
              {session?.id === member.id ? (
                <Link href="/settings" className="eg-btn eg-btn-outline">
                  Edit profile
                </Link>
              ) : null}
              {!session ? (
                <Link href={`/login?next=/members/${member.id}`} className="eg-btn eg-btn-accent">
                  Sign in to message
                </Link>
              ) : null}
            </div>
          </aside>
        </div>

        <div className="auction-board member-board">
          <section>
            <h2>House notes</h2>
            {facts.length ? (
              <dl className="auction-facts">
                {facts.map(([label, value]) => (
                  <div key={label}>
                    <dt>{label}</dt>
                    <dd>
                      {label === "Website" && website ? (
                        <a href={website.startsWith("http") ? website : `https://${website}`} rel="noreferrer">
                          {website.replace(/^https?:\/\//, "")}
                        </a>
                      ) : (
                        value
                      )}
                    </dd>
                  </div>
                ))}
              </dl>
            ) : (
              <p className="text-muted">No trade notes on file.</p>
            )}
          </section>

          <section>
            <h2>From the floor</h2>
            {member.posts.length === 0 ? (
              <p className="text-muted">No public notes yet.</p>
            ) : (
              <div className="member-notes">
                {member.posts.map((post) => (
                  <article key={post.id} className="profile-post">
                    <div className="floor-item__meta">
                      <span className={`kind-pill kind-pill--${post.kind}`}>
                        {KIND_LABEL[post.kind] || post.kind}
                      </span>
                      <time>
                        {post.createdAt.toLocaleDateString(undefined, { month: "short", day: "numeric" })}
                      </time>
                    </div>
                    <h3>
                      <Link href={`/feed/${post.id}`}>{post.title}</Link>
                    </h3>
                    <p>{post.body}</p>
                  </article>
                ))}
              </div>
            )}
          </section>
        </div>

        <section className="member-inventory">
          <div className="portal-col__head">
            <div>
              <p className="eg-eyebrow">On the tray</p>
              <h2>Inventory</h2>
            </div>
            {listings.length ? <p>{listings.length} lots</p> : null}
          </div>
          {listings.length === 0 ? (
            <p className="text-muted">No stones listed on the floor.</p>
          ) : (
            <div className="dir-grid dir-grid--profile">
              {listings.map((listing) => (
                <ListingCard
                  key={listing.id}
                  href={`/search/${listing.id}`}
                  title={listing.title}
                  imageUrl={listing.imageUrl}
                  gemType={gemTypeLabel(listing.gemType)}
                  origin={listing.origin}
                  color={listing.color}
                  treatment={listing.treatment}
                  certification={listing.certification}
                  weightCt={listing.weightCt}
                  askingPrice={listing.askingPrice}
                  seller={member.profile?.company || member.name}
                  wholesale={listing.wholesaleOnly}
                  availability={listing.availability}
                />
              ))}
            </div>
          )}
        </section>
      </div>
    </div>
  );
}
