'use client'

import { useSearchParams, useRouter } from 'next/navigation'
import { Suspense } from 'react'
import { ComposeForm } from '@/components/email/compose-form'

function ComposeContent() {
  const searchParams = useSearchParams()
  const router = useRouter()

  const to = searchParams.get('to') || ''
  const subject = searchParams.get('subject') || ''
  const inReplyTo = searchParams.get('inReplyTo') || undefined
  let references: string[] | undefined
  try {
    const refsParam = searchParams.get('references')
    if (refsParam) references = JSON.parse(refsParam)
  } catch {
    // Ignore invalid JSON
  }

  return (
    <div className="p-6">
      <h2 className="text-lg font-semibold mb-4">
        {inReplyTo ? 'Reply' : subject?.startsWith('Fwd:') ? 'Forward' : 'New Message'}
      </h2>
      <ComposeForm
        defaultTo={to}
        defaultSubject={subject}
        inReplyTo={inReplyTo}
        references={references}
        onCancel={() => router.back()}
      />
    </div>
  )
}

export default function ComposePage() {
  return (
    <Suspense fallback={<div className="p-6">Loading...</div>}>
      <ComposeContent />
    </Suspense>
  )
}
