import { verifySigningToken, createDownloadToken } from '@/lib/signing/token';
import { db } from '@/lib/db';
import { signingTokens, documents } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';

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

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

  // Verify signing token to get documentId (allow expired — confirmation page visited after signing)
  let documentId: string | null = null;
  let jti: string | null = null;
  try {
    const payload = await verifySigningToken(token);
    documentId = payload.documentId;
    jti = payload.jti;
  } catch {
    // Token expired is OK here — signing may have happened right before expiry
    // documentId/jti remain null — handled below
  }

  if (!documentId) {
    return (
      <div
        style={{
          padding: '40px',
          textAlign: 'center',
          fontFamily: 'Georgia, serif',
          color: '#1B2B4B',
        }}
      >
        Document not found.
      </div>
    );
  }

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

  // Get signed timestamp from signingTokens.usedAt
  let signedAt: Date | null = null;
  if (jti) {
    const tokenRow = await db.query.signingTokens.findFirst({
      where: eq(signingTokens.jti, jti),
    });
    signedAt = tokenRow?.usedAt ?? doc?.signedAt ?? null;
  }

  if (!doc || !doc.signedFilePath) {
    return (
      <div
        style={{
          minHeight: '100vh',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: '#FAF9F7',
          fontFamily: 'Georgia, serif',
        }}
      >
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <h1 style={{ color: '#1B2B4B' }}>Document not yet available</h1>
          <p style={{ color: '#555' }}>Please check back shortly.</p>
        </div>
      </div>
    );
  }

  // Generate 15-minute download token for client copy
  const downloadToken = await createDownloadToken(doc.id);
  const downloadUrl = `/api/sign/${token}/download?dt=${downloadToken}`;

  const formattedDate = signedAt
    ? signedAt.toLocaleString('en-US', {
        month: 'long',
        day: 'numeric',
        year: 'numeric',
        hour: 'numeric',
        minute: '2-digit',
      })
    : 'Just now';

  return (
    <div
      style={{
        minHeight: '100vh',
        backgroundColor: '#FAF9F7',
        fontFamily: 'Georgia, serif',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <div style={{ textAlign: 'center', maxWidth: '480px', padding: '48px 32px' }}>
        {/* Success checkmark */}
        <div
          style={{
            width: '72px',
            height: '72px',
            borderRadius: '50%',
            backgroundColor: '#1B2B4B',
            color: '#C9A84C',
            fontSize: '36px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            margin: '0 auto 24px',
          }}
        >
          &#10003;
        </div>
        <h1 style={{ color: '#1B2B4B', fontSize: '26px', marginBottom: '8px' }}>
          You&apos;ve signed
        </h1>
        <p
          style={{
            color: '#1B2B4B',
            fontSize: '20px',
            fontWeight: 'bold',
            marginBottom: '8px',
          }}
        >
          {doc.name}
        </p>
        <p style={{ color: '#888', fontSize: '14px', marginBottom: '32px' }}>
          Signed on {formattedDate}
        </p>
        <a
          href={downloadUrl}
          style={{
            display: 'inline-block',
            backgroundColor: '#C9A84C',
            color: '#fff',
            padding: '12px 28px',
            borderRadius: '4px',
            textDecoration: 'none',
            fontWeight: 'bold',
            fontSize: '15px',
          }}
        >
          Download your copy
        </a>
        <p style={{ color: '#aaa', fontSize: '12px', marginTop: '16px' }}>
          Download link valid for 15 minutes.
        </p>
      </div>
    </div>
  );
}
