import { Suspense } from 'react'
import { redirect } from 'next/navigation'
import BibleReader from './reader'
import { prisma } from '@/lib/db'

interface PageProps {
  searchParams: Promise<{
    version?: string
    book?: string
    chapter?: string
    verse?: string
  }>
  params: Promise<{
    locale: string
  }>
}

// Helper function to convert UUIDs to SEO-friendly slugs
async function convertToSeoUrl(versionId: string, bookId: string, chapter: string, locale: string) {
  try {
    const version = await prisma.bibleVersion.findUnique({
      where: { id: versionId }
    })

    const book = await prisma.bibleBook.findUnique({
      where: { id: bookId }
    })

    if (version && book) {
      const versionSlug = version.abbreviation.toLowerCase()
      const bookSlug = book.bookKey.toLowerCase()
      return `/${locale}/bible/${versionSlug}/${bookSlug}/${chapter}`
    }
  } catch (error) {
    console.error('Error converting to SEO URL:', error)
  }
  return null
}

export default async function BiblePage({ searchParams, params }: PageProps) {
  const { version, book, chapter } = await searchParams
  const { locale } = await params

  // If we have the old URL format with UUIDs, redirect to SEO-friendly URL
  if (version && book && chapter) {
    const seoUrl = await convertToSeoUrl(version, book, chapter, locale)
    if (seoUrl) {
      redirect(seoUrl)
    }
  }

  return (
    <Suspense fallback={
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        minHeight: '200px'
      }}>
        Loading Bible reader...
      </div>
    }>
      <BibleReader />
    </Suspense>
  )
}