import { verifySigningToken } from '@/lib/signing/token';
import { logAuditEvent } from '@/lib/signing/audit';
import { db } from '@/lib/db';
import { signingTokens, documents } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
import { headers } from 'next/headers';
import { SigningPageClientWrapper } from './_components/SigningPageClientWrapper';

interface Props {
  params: Promise<{ token: string }>;
}

export default async function SignPage({ params }: Props) {
  const { token } = await params;

  // CRITICAL: Validate BEFORE rendering any signing UI — no canvas flash on invalid tokens
  let payload: { documentId: string; jti: string } | null = null;
  let isExpired = false;
  try {
    payload = await verifySigningToken(token);
  } catch {
    isExpired = true;
  }

  if (isExpired) {
    return <ErrorPage type="expired" />;
  }

  if (!payload) {
    return <ErrorPage type="invalid" />;
  }

  // Check one-time use
  const tokenRow = await db.query.signingTokens.findFirst({
    where: eq(signingTokens.jti, payload.jti),
  });

  if (!tokenRow) return <ErrorPage type="invalid" />;

  if (tokenRow.usedAt !== null) {
    return <ErrorPage type="used" signedAt={tokenRow.usedAt} />;
  }

  const doc = await db.query.documents.findFirst({
    where: eq(documents.id, payload.documentId),
  });

  if (!doc || !doc.preparedFilePath) return <ErrorPage type="invalid" />;

  // Log audit events and update status to Viewed
  const headersList = await headers();
  const ip = headersList.get('x-forwarded-for')?.split(',')[0].trim() ?? 'unknown';
  const ua = headersList.get('user-agent') ?? 'unknown';
  await Promise.all([
    logAuditEvent({ documentId: payload.documentId, eventType: 'link_opened', ipAddress: ip, userAgent: ua }),
    logAuditEvent({ documentId: payload.documentId, eventType: 'document_viewed', ipAddress: ip, userAgent: ua }),
    db.update(documents).set({ status: 'Viewed' }).where(eq(documents.id, payload.documentId)),
  ]);

  return (
    <SigningPageClientWrapper
      token={token}
      documentName={doc.name}
      signatureFields={doc.signatureFields ?? []}
    />
  );
}

function ErrorPage({
  type,
  signedAt,
}: {
  type: 'expired' | 'used' | 'invalid';
  signedAt?: Date | null;
}) {
  const messages = {
    expired: {
      title: 'Link Expired',
      body: 'This signing link has expired. Please contact Teressa Copeland for a new link.',
    },
    used: {
      title: 'Already Signed',
      body: `This document has already been signed${
        signedAt
          ? ' on ' +
            signedAt.toLocaleDateString('en-US', {
              month: 'long',
              day: 'numeric',
              year: 'numeric',
            })
          : ''
      }.`,
    },
    invalid: {
      title: 'Invalid Link',
      body: 'This signing link is not valid. Please check your email for the correct link.',
    },
  };
  const { title, body } = messages[type];
  return (
    <div
      style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#FAF9F7',
        fontFamily: 'Georgia, serif',
      }}
    >
      <div style={{ textAlign: 'center', maxWidth: '420px', padding: '40px' }}>
        <div style={{ fontSize: '48px', marginBottom: '16px' }}>
          {type === 'used' ? '\u2713' : '\u26a0'}
        </div>
        <h1 style={{ color: '#1B2B4B', fontSize: '24px', marginBottom: '12px' }}>{title}</h1>
        <p style={{ color: '#555', fontSize: '16px', lineHeight: '1.6' }}>{body}</p>
      </div>
    </div>
  );
}
