import { Metadata } from 'next'
import { auth } from '@/auth'
import { redirect } from 'next/navigation'
import { getCanvases, createCanvas } from '@/app/actions/canvas-actions'
import { LabHeader } from '@/components/lab/lab-header'
import { CanvasWrapper } from '@/components/lab/canvas-wrapper'

export const metadata: Metadata = {
  title: 'Le Lab | Memento',
  description: 'Visualisez et connectez vos idées sur un canvas interactif',
}

export const dynamic = 'force-dynamic'
export const revalidate = 0

export default async function LabPage(props: {
  searchParams: Promise<{ id?: string }>
}) {
  const searchParams = await props.searchParams
  const id = searchParams.id
  
  const session = await auth()
  if (!session?.user?.id) redirect('/login')

  const canvases = await getCanvases()
  
  // Resolve current canvas correctly
  const currentCanvasId = searchParams.id || (canvases.length > 0 ? canvases[0].id : undefined)
  const currentCanvas = currentCanvasId ? canvases.find(c => c.id === currentCanvasId) : undefined

  // Wrapper for server action creation
  async function handleCreate() {
    'use server'
    const newCanvas = await createCanvas()
    redirect(`/lab?id=${newCanvas.id}`)
  }

  return (
    <div className="flex-1 flex flex-col h-full bg-slate-50 dark:bg-[#1a1c22] overflow-hidden">
      <LabHeader 
        canvases={canvases} 
        currentCanvasId={currentCanvasId ?? null} 
        onCreateCanvas={handleCreate}
      />

      <div className="flex-1 relative">
        <CanvasWrapper 
          key={currentCanvasId || 'new'}
          canvasId={currentCanvas?.id} 
          name={currentCanvas?.name || "Nouvel Espace de Pensée"}
          initialData={currentCanvas?.data}
        />
      </div>
    </div>
  )
}
