import Link from 'next/link'
import { Map as MapIcon, MapPin, ImagePlus } from 'lucide-react'
import { PageShell, PageHeader } from '@/components/page-shell'
import { BackButton } from '@/components/back-button'
import { db } from '@/lib/db'
import { NewMapDialog } from './new-map-dialog'

export const dynamic = 'force-dynamic'

export default async function MapsPage() {
  const [maps, locations] = await Promise.all([
    db.map.findMany({
      orderBy: [{ locationId: 'asc' }, { createdAt: 'asc' }],
      include: {
        location: { select: { id: true, path: true } },
        pins: { select: { id: true, x: true, y: true } },
      },
    }),
    db.location.findMany({
      orderBy: [{ path: 'asc' }],
      select: { id: true, path: true },
    }),
  ])

  const locationOptions = locations.map(l => ({ id: l.id, path: l.path }))

  return (
    <PageShell>
      <div className="pt-2">
        <PageHeader
          title="Maps"
          back={<BackButton fallbackHref="/locations" />}
          action={
            <NewMapDialog
              locations={locationOptions}
              trigger={
                <button className="inline-flex items-center gap-1 h-10 px-3 rounded-lg bg-primary text-primary-foreground text-sm font-medium">
                  <ImagePlus className="size-4" /> New
                </button>
              }
            />
          }
        />

        {maps.length === 0 ? (
          <div className="rounded-xl border bg-card p-8 text-center text-muted-foreground">
            <MapIcon className="size-8 mx-auto mb-2 text-muted-foreground/60" />
            <div className="text-sm">No maps yet.</div>
            <div className="text-xs text-muted-foreground/70 mt-2 max-w-sm mx-auto">
              Upload a drone aerial or floor plan, then tap on it to pin
              locations.
            </div>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {maps.map(m => (
              <Link
                key={m.id}
                href={`/locations/maps/${m.id}`}
                className="block rounded-xl border bg-card overflow-hidden hover:bg-accent/40"
              >
                <div
                  className="relative bg-muted"
                  style={{ aspectRatio: `${m.width} / ${m.height}` }}
                >
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={`/api/uploads/${m.imagePath}`}
                    alt={m.name}
                    className="absolute inset-0 w-full h-full object-contain"
                  />
                  {m.pins.map(p => (
                    <div
                      key={p.id}
                      style={{ left: `${p.x * 100}%`, top: `${p.y * 100}%` }}
                      className="absolute -translate-x-1/2 -translate-y-full pointer-events-none"
                    >
                      <MapPin className="size-4 fill-primary text-primary-foreground drop-shadow" />
                    </div>
                  ))}
                </div>
                <div className="p-3">
                  <div className="font-medium truncate">{m.name}</div>
                  <div className="text-xs text-muted-foreground truncate">
                    {m.location?.path ?? ''}
                  </div>
                  <div className="text-xs text-muted-foreground mt-1">
                    {m.pins.length} pin{m.pins.length === 1 ? '' : 's'}
                  </div>
                </div>
              </Link>
            ))}
          </div>
        )}
      </div>
    </PageShell>
  )
}
