import { auth } from '@/lib/auth';
import { redirect } from 'next/navigation';
import { db } from '@/lib/db';
import { documents, clients } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
import Link from 'next/link';
import { DocumentPageClient } from './_components/DocumentPageClient';
import { createAgentDownloadToken } from '@/lib/signing/token';

export default async function DocumentPage({
  params,
}: {
  params: Promise<{ docId: string }>;
}) {
  const session = await auth();
  if (!session) redirect('/login');

  const { docId } = await params;

  const [doc, docClient] = await Promise.all([
    db.query.documents.findFirst({ where: eq(documents.id, docId) }),
    db.select({ email: clients.email, name: clients.name, propertyAddress: clients.propertyAddress })
      .from(clients)
      .innerJoin(documents, eq(documents.clientId, clients.id))
      .where(eq(documents.id, docId))
      .limit(1)
      .then(r => r[0] ?? null),
  ]);

  if (!doc) redirect('/portal/dashboard');

  // Generate agent download URL server-side for Signed documents
  // Must be done here (server component) — PreparePanel is 'use client' and cannot call createAgentDownloadToken
  const agentDownloadUrl = doc.signedFilePath
    ? `/api/documents/${docId}/download?adt=${await createAgentDownloadToken(docId)}`
    : null;

  return (
    <div className="max-w-5xl mx-auto px-4 py-6">
      <div className="mb-4 flex items-center justify-between">
        <div>
          <Link
            href={`/portal/clients/${doc.clientId}`}
            className="inline-flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-blue-600 border border-blue-200 rounded-md bg-blue-50 hover:bg-blue-100 hover:border-blue-300 transition-colors"
          >
            &larr; Back to {docClient?.name ?? 'Client'}
          </Link>
          <h1 className="text-2xl font-bold mt-1">{doc.name}</h1>
          <p className="text-sm text-gray-500">
            {docClient?.name} &middot; <span className="capitalize">{doc.status}</span>
          </p>
        </div>
      </div>

      <DocumentPageClient
        docId={docId}
        docStatus={doc.status}
        defaultEmail={docClient?.email ?? ''}
        clientName={docClient?.name ?? ''}
        agentDownloadUrl={agentDownloadUrl}
        signedAt={doc.signedAt ?? null}
        clientPropertyAddress={docClient?.propertyAddress ?? null}
        initialSigners={doc.signers ?? []}
      />
    </div>
  );
}
