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 { PdfViewerWrapper } from './_components/PdfViewerWrapper';

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

  const { docId } = await params;

  const doc = await db.query.documents.findFirst({
    where: eq(documents.id, docId),
    with: { client: true },
  });

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

  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 {doc.client?.name ?? 'Client'}
          </Link>
          <h1 className="text-2xl font-bold mt-1">{doc.name}</h1>
          <p className="text-sm text-gray-500">{doc.client?.name}</p>
        </div>
      </div>
      <PdfViewerWrapper docId={docId} />
    </div>
  );
}
