import { notFound } from 'next/navigation'
import { PageShell, PageHeader } from '@/components/page-shell'
import { BackButton } from '@/components/back-button'
import { db } from '@/lib/db'
import { listMapsForPicker } from '@/lib/maps'
import { EditItemForm } from './edit-item-form'

export const dynamic = 'force-dynamic'

export default async function EditItemPage({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id } = await params
  const [item, locations, maps] = await Promise.all([
    db.item.findUnique({
      where: { id },
      include: { tags: true },
    }),
    db.location.findMany({
      orderBy: [{ path: 'asc' }],
      select: { id: true, path: true },
    }),
    listMapsForPicker(),
  ])
  if (!item) notFound()

  return (
    <PageShell>
      <div className="pt-2">
        <PageHeader
          title="Edit item"
          back={<BackButton fallbackHref={`/items/${id}`} />}
        />
        <EditItemForm
          item={{
            id: item.id,
            name: item.name,
            description: item.description,
            category: item.category,
            brand: item.brand,
            serialNumber: item.serialNumber,
            notes: item.notes,
            caption: item.caption,
            qty: item.qty,
            value: item.value?.toString() || '',
            status: item.status,
            locationId: item.locationId,
            tags: item.tags.map(t => t.name),
          }}
          locations={locations}
          maps={maps}
        />
      </div>
    </PageShell>
  )
}
