import Link from 'next/link'
import { notFound } from 'next/navigation'
import { PageShell, PageHeader } from '@/components/page-shell'
import { BackButton } from '@/components/back-button'
import { db } from '@/lib/db'
import { MapView } from './map-view'
import { EditableMapTitle } from './editable-title'

export const dynamic = 'force-dynamic'

export default async function MapDetailPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>
  searchParams: Promise<{ focus?: string }>
}) {
  const { id } = await params
  const { focus } = await searchParams
  const [map, locations] = await Promise.all([
    db.map.findUnique({
      where: { id },
      include: {
        location: true,
        pins: {
          include: {
            location: {
              select: {
                id: true,
                path: true,
                name: true,
                ownMaps: { select: { id: true } },
                _count: { select: { items: true } },
              },
            },
          },
        },
      },
    }),
    db.location.findMany({
      orderBy: [{ path: 'asc' }],
      select: { id: true, path: true },
    }),
  ])
  if (!map) notFound()

  // A map may only pin locations that live *inside* the location it depicts.
  // Restricting the picker to the owner's subtree is what prevents the
  // cross-hierarchy drift we saw with the pantry (a Sunrock-level location
  // pinned onto a House map). The owner's descendants are exactly the rows
  // whose path is prefixed by "<owner path> > ".
  const pinnable = locations.filter(l =>
    l.path.startsWith(map.location.path + ' > '),
  )

  return (
    <PageShell>
      <div className="pt-2">
        <PageHeader
          title={<EditableMapTitle mapId={map.id} initial={map.name} />}
          back={<BackButton fallbackHref="/locations/maps" />}
        />
        <div className="text-xs text-muted-foreground mb-2">
          Map of{' '}
          <Link
            href={`/locations/${map.location.id}`}
            className="underline text-foreground"
          >
            {map.location.path}
          </Link>
        </div>

        <MapView
          mapId={map.id}
          imagePath={map.imagePath}
          width={map.width}
          height={map.height}
          pins={map.pins.map(p => ({
            id: p.id,
            x: p.x,
            y: p.y,
            locationId: p.location.id,
            locationName: p.location.name,
            locationPath: p.location.path,
            hasOwnMap: p.location.ownMaps.length > 0,
            itemCount: p.location._count.items,
          }))}
          locations={pinnable}
          focusLocationId={focus}
        />
      </div>
    </PageShell>
  )
}
