import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { documents, clients, signingTokens } from "@/lib/db/schema";
import { eq, desc, sql } from "drizzle-orm";
import { DocumentsTable } from "../../_components/DocumentsTable";
import { DashboardFilters } from "../../_components/DashboardFilters";

const VALID_STATUSES = ["Draft", "Sent", "Viewed", "Signed"] as const;
type ValidStatus = (typeof VALID_STATUSES)[number];

export default async function DashboardPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string }>;
}) {
  const session = await auth();
  const { status } = await searchParams;

  const allRows = await db
    .select({
      id: documents.id,
      name: documents.name,
      status: documents.status,
      sentAt: documents.sentAt,
      signedAt: documents.signedAt,
      clientName: clients.name,
      clientId: documents.clientId,
      signers: documents.signers,
    })
    .from(documents)
    .leftJoin(clients, eq(documents.clientId, clients.id))
    .orderBy(desc(documents.createdAt));

  // Fetch signing token counts per document in one query (avoids N+1)
  const tokenCounts = await db
    .select({
      documentId: signingTokens.documentId,
      total: sql<number>`count(*)`.as("total"),
      signed: sql<number>`count(${signingTokens.usedAt})`.as("signed"),
    })
    .from(signingTokens)
    .groupBy(signingTokens.documentId);

  const tokenMap = new Map(
    tokenCounts.map((t) => [
      t.documentId,
      { total: Number(t.total), signed: Number(t.signed) },
    ])
  );

  const filteredRows =
    status && (VALID_STATUSES as readonly string[]).includes(status)
      ? allRows.filter((r) => r.status === (status as ValidStatus))
      : allRows;

  const enrichedRows = filteredRows.map((row) => {
    const tc = tokenMap.get(row.id);
    return {
      ...row,
      signedCount: tc?.signed ?? null,
      totalSigners: tc?.total ?? null,
      hasMultipleSigners: Array.isArray(row.signers) && row.signers.length > 0,
    };
  });

  const firstName = session?.user?.email?.split("@")[0] ?? "Agent";

  return (
    <div>
      <div style={{ marginBottom: "1.5rem" }}>
        <h1 style={{ color: "#1B2B4B", fontSize: "1.5rem", fontWeight: 700, marginBottom: "0.25rem" }}>
          Welcome back, {firstName}
        </h1>
        <p style={{ color: "#6B7280", fontSize: "0.875rem" }}>All documents across your clients</p>
      </div>

      <div style={{ backgroundColor: "white", borderRadius: "1rem", boxShadow: "0 1px 4px rgba(0,0,0,0.07)", overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "center", gap: "0.75rem", padding: "1rem 1.5rem", borderBottom: "1px solid #F3F4F6" }}>
          <span style={{ fontSize: "0.875rem", color: "#6B7280" }}>Filter by status:</span>
          <DashboardFilters currentStatus={status} />
        </div>
        <DocumentsTable rows={enrichedRows} showClientColumn={true} />
      </div>
    </div>
  );
}
