import Link from 'next/link'
import { notFound } from 'next/navigation'
import { Pencil, MapPin, Quote } from 'lucide-react'
import { PageShell, PageHeader } from '@/components/page-shell'
import { BackButton } from '@/components/back-button'
import { db } from '@/lib/db'
import { PhotosSection } from './photos-section'
import { PendingNoteSection } from './pending-note-section'

export const dynamic = 'force-dynamic'

const statusBadge: Record<string, string> = {
  ACTIVE: 'bg-emerald-100 text-emerald-800',
  LOANED: 'bg-amber-100 text-amber-800',
  DISPOSED: 'bg-zinc-100 text-zinc-600',
  LOST: 'bg-rose-100 text-rose-800',
}

export default async function ItemDetailPage({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id } = await params
  const item = await db.item.findUnique({
    where: { id },
    include: {
      location: true,
      tags: true,
      photos: { orderBy: [{ position: 'asc' }, { createdAt: 'asc' }] },
      addedBy: { select: { name: true } },
    },
  })
  if (!item) notFound()

  return (
    <PageShell>
      <div className="pt-2">
        <PageHeader
          title={item.name}
          back={<BackButton fallbackHref="/" />}
          action={
            <Link
              href={`/items/${item.id}/edit`}
              className="inline-flex items-center gap-1 h-10 px-3 rounded-lg border bg-card text-sm font-medium"
            >
              <Pencil className="size-4" />
              Edit
            </Link>
          }
        />

        <PhotosSection itemId={item.id} photos={item.photos} />

        <div className="mt-4 space-y-3">
          <div className="flex flex-wrap items-center gap-2">
            <span className={`text-xs font-medium uppercase tracking-wide px-2 py-0.5 rounded ${statusBadge[item.status]}`}>
              {item.status.toLowerCase()}
            </span>
            {item.qty > 1 && (
              <span className="text-xs text-muted-foreground">×{item.qty}</span>
            )}
            {item.tags.map(t => (
              <Link
                key={t.id}
                href={`/?tag=${encodeURIComponent(t.name)}`}
                className="text-xs px-2 py-0.5 rounded-full bg-accent text-accent-foreground"
              >
                #{t.name}
              </Link>
            ))}
          </div>

          <Link
            href={`/locations/${item.locationId}`}
            className="flex items-center gap-2 p-3 rounded-xl border bg-card text-sm hover:bg-accent/40"
          >
            <MapPin className="size-4 text-muted-foreground shrink-0" />
            <span className="truncate">{item.location.path}</span>
          </Link>

          {item.caption && (
            <div className="flex gap-2 p-3 rounded-xl border bg-card text-sm">
              <Quote className="size-4 text-muted-foreground shrink-0 mt-0.5" />
              <span className="italic">{item.caption}</span>
            </div>
          )}

          <PendingNoteSection
            itemId={item.id}
            initialNote={item.pendingNote}
            initialVoicePath={item.voiceNotePath}
            initialVoiceMime={item.voiceNoteMime}
            needsAIReview={item.needsAIReview}
          />

          {item.description && (
            <Section label="Description">{item.description}</Section>
          )}
          {item.notes && <Section label="Notes">{item.notes}</Section>}

          <dl className="grid grid-cols-2 gap-x-4 gap-y-2 p-3 rounded-xl border bg-card text-sm">
            {item.category && <KV label="Category" value={item.category} />}
            {item.brand && <KV label="Brand" value={item.brand} />}
            {item.serialNumber && <KV label="Serial" value={item.serialNumber} />}
            {item.value && (
              <KV label="Value" value={`$${item.value.toString()}`} />
            )}
            <KV
              label="Added"
              value={`${new Date(item.createdAt).toLocaleDateString()}${item.addedBy ? ` · ${item.addedBy.name}` : ''}`}
            />
          </dl>
        </div>
      </div>
    </PageShell>
  )
}

function Section({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="p-3 rounded-xl border bg-card">
      <div className="text-xs uppercase tracking-wide text-muted-foreground mb-1">{label}</div>
      <div className="text-sm whitespace-pre-wrap">{children}</div>
    </div>
  )
}

function KV({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <dt className="text-xs text-muted-foreground">{label}</dt>
      <dd className="font-medium">{value}</dd>
    </div>
  )
}
