import { auth } from '@/lib/auth';
import { redirect } from 'next/navigation';
import { db } from '@/lib/db';
import { documents, clients } from '@/lib/db/schema';
import { eq, asc } from 'drizzle-orm';
import Link from 'next/link';
import { PdfViewerWrapper } from './_components/PdfViewerWrapper';
import { PreparePanel } from './_components/PreparePanel';

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

  const { docId } = await params;

  const [doc, allClients] = await Promise.all([
    db.query.documents.findFirst({
      where: eq(documents.id, docId),
      with: { client: true },
    }),
    db.select().from(clients).orderBy(asc(clients.name)),
  ]);

  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} &middot; <span className="capitalize">{doc.status}</span>
          </p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2">
          <PdfViewerWrapper docId={docId} />
        </div>
        <div className="lg:col-span-1">
          <PreparePanel
            docId={docId}
            clients={allClients}
            currentClientId={doc.assignedClientId ?? doc.clientId}
            currentStatus={doc.status}
          />
        </div>
      </div>
    </div>
  );
}
