import Link from "next/link";
import { notFound } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { requireUser } from "@/lib/auth/session";
import { PageHeader } from "@/components/layout/page-header";
import { Button } from "@/components/ui/button";
import { MessagesClient, type ThreadMessage } from "./messages-client";

type RawMessage = {
  id: string;
  body: string;
  created_at: string;
  sender: string;
  sender_user_id: string | null;
  sender_user?: { full_name: string } | { full_name: string }[] | null;
};

function embeddedName(rel: RawMessage["sender_user"]): string {
  if (!rel) return "";
  const r = Array.isArray(rel) ? rel[0] : rel;
  return r?.full_name ?? "";
}

export default async function StaffMessagesPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const user = await requireUser();
  const supabase = await createClient();

  const { data: app } = await supabase
    .from("student_applications")
    .select("applicant_name, student_user_id")
    .eq("id", id)
    .single();
  if (!app) notFound();

  // Fetch the thread. Attempt the embedded sender name; fall back to a
  // separate name lookup if the relationship does not resolve.
  let raw: RawMessage[] = [];
  let nameById = new Map<string, string>();

  const withEmbed = await supabase
    .from("student_messages")
    .select("id, body, created_at, sender, sender_user_id, sender_user:users(full_name)")
    .eq("student_application_id", id)
    .order("created_at");

  if (withEmbed.error) {
    const plain = await supabase
      .from("student_messages")
      .select("id, body, created_at, sender, sender_user_id")
      .eq("student_application_id", id)
      .order("created_at");
    raw = (plain.data as RawMessage[]) ?? [];

    const ids = [
      ...new Set(raw.map((m) => m.sender_user_id).filter(Boolean) as string[]),
    ];
    if (ids.length > 0) {
      const { data: users } = await supabase
        .from("users")
        .select("id, full_name")
        .in("id", ids);
      nameById = new Map(
        (users ?? []).map((u) => [u.id, u.full_name as string]),
      );
    }
  } else {
    raw = (withEmbed.data as RawMessage[]) ?? [];
  }

  const messages: ThreadMessage[] = raw.map((m) => ({
    id: m.id,
    body: m.body,
    created_at: m.created_at,
    sender: m.sender,
    senderName:
      embeddedName(m.sender_user) ||
      (m.sender_user_id ? nameById.get(m.sender_user_id) ?? "" : ""),
    // For staff, "mine" means staff-authored messages (aligned right).
    mine: m.sender_user_id === user.id || m.sender === "staff",
  }));

  return (
    <div>
      <PageHeader
        title={`Messages — ${app.applicant_name}`}
        breadcrumb="Application / Student / Messages"
        action={
          <Button asChild variant="outline">
            <Link href={`/applications/student/${id}`}>Back</Link>
          </Button>
        }
      />

      {!app.student_user_id && (
        <div className="mb-4 rounded-md border border-brand-orange/40 bg-brand-orange/10 px-4 py-3 text-sm text-foreground">
          This student hasn&apos;t been invited to the portal yet. You can still
          read and post messages — the student will see them once invited.
        </div>
      )}

      <div className="mx-auto max-w-2xl">
        <MessagesClient applicationId={id} messages={messages} />
      </div>
    </div>
  );
}
