import Link from 'next/link'
import { ChevronRight, FolderTree, Plus, Map as MapIcon } from 'lucide-react'
import { PageShell, PageHeader } from '@/components/page-shell'
import { db } from '@/lib/db'
import { listLocationTree } from '@/lib/locations'
import { AddLocationDialog } from './add-location-dialog'

export const dynamic = 'force-dynamic'

interface Node {
  id: string
  name: string
  parentId: string | null
  path: string
  _count: { items: number; children: number }
  children: Node[]
}

function buildTree(rows: Awaited<ReturnType<typeof listLocationTree>>): Node[] {
  const byId = new Map<string, Node>()
  rows.forEach(r => byId.set(r.id, { ...r, children: [] }))
  const roots: Node[] = []
  rows.forEach(r => {
    const node = byId.get(r.id)!
    if (r.parentId && byId.has(r.parentId)) byId.get(r.parentId)!.children.push(node)
    else roots.push(node)
  })
  return roots
}

function TreeNode({ node, depth }: { node: Node; depth: number }) {
  return (
    <div>
      <Link
        href={`/locations/${node.id}`}
        className="flex items-center gap-2 py-2 pr-2 rounded-lg hover:bg-accent/40"
        style={{ paddingLeft: `${depth * 1 + 0.5}rem` }}
      >
        <FolderTree className="size-4 text-muted-foreground shrink-0" />
        <span className="font-medium truncate flex-1">{node.name}</span>
        <span className="text-xs text-muted-foreground tabular-nums">
          {node._count.items}
        </span>
        <ChevronRight className="size-4 text-muted-foreground" />
      </Link>
      {node.children.map(c => (
        <TreeNode key={c.id} node={c} depth={depth + 1} />
      ))}
    </div>
  )
}

export default async function LocationsPage() {
  const [rows, mapCount] = await Promise.all([
    listLocationTree(),
    db.map.count(),
  ])
  const tree = buildTree(rows)

  return (
    <PageShell>
      <div className="pt-2">
        <PageHeader
          title="Places"
          action={<AddLocationDialog locations={rows} trigger={
            <button className="inline-flex items-center gap-1 h-10 px-3 rounded-lg bg-primary text-primary-foreground text-sm font-medium">
              <Plus className="size-4" /> Add
            </button>
          } />}
        />

        <Link
          href="/locations/maps"
          className="flex items-center gap-3 p-3 rounded-xl border bg-card hover:bg-accent/40 mb-3"
        >
          <MapIcon className="size-5 text-muted-foreground" />
          <div className="flex-1">
            <div className="font-medium text-sm">Maps</div>
            <div className="text-xs text-muted-foreground">
              {mapCount === 0
                ? 'No maps yet — upload a drone aerial or floor plan'
                : `${mapCount} map${mapCount === 1 ? '' : 's'} · tap to view & pin`}
            </div>
          </div>
          <ChevronRight className="size-4 text-muted-foreground" />
        </Link>

        <div className="rounded-xl border bg-card divide-y divide-border/60">
          {tree.length === 0 ? (
            <div className="p-6 text-center text-muted-foreground text-sm">
              No locations yet.
            </div>
          ) : (
            tree.map(n => <TreeNode key={n.id} node={n} depth={0} />)
          )}
        </div>
      </div>
    </PageShell>
  )
}
