import Link from 'next/link'
import { PageShell, PageHeader } from '@/components/page-shell'
import { db } from '@/lib/db'
import { getLatestSession, getQueueDepth } from '@/lib/ai-review-session'
import { ReviewCard } from './review-card'
import { StartAIPass } from './start-ai-pass'

export const dynamic = 'force-dynamic'

export default async function IdentifyPage() {
  const [jobs, queueDepth, latest] = await Promise.all([
    db.identificationJob.findMany({
      where: { status: { in: ['PENDING', 'DONE'] } },
      include: {
        photo: {
          include: {
            item: {
              include: {
                tags: true,
                location: true,
                photos: { orderBy: [{ isPrimary: 'desc' }, { createdAt: 'asc' }] },
              },
            },
          },
        },
      },
      orderBy: [{ status: 'asc' }, { createdAt: 'asc' }],
      take: 50,
    }),
    getQueueDepth(),
    getLatestSession(),
  ])

  const mode = process.env.IDENTIFY_MODE || 'off'

  return (
    <PageShell>
      <div className="pt-2 space-y-4">
        <PageHeader
          title="Identify"
          action={
            <span className="text-xs text-muted-foreground px-2 py-1 rounded-full bg-accent">
              mode: {mode}
            </span>
          }
        />

        <StartAIPass initial={{ queueDepth, latest }} />

        {jobs.length > 0 && (
          <div className="space-y-3">
            {jobs.map(j => (
              <ReviewCard
                key={j.id}
                job={{
                  id: j.id,
                  status: j.status,
                  suggestedName: j.suggestedName,
                  suggestedCategory: j.suggestedCategory,
                  suggestedBrand: j.suggestedBrand,
                  suggestedTags: j.suggestedTags,
                  confidence: j.confidence,
                  errorMessage: j.errorMessage,
                  thumbPaths: j.photo.item.photos.map(p => p.thumbPath),
                  itemId: j.photo.item.id,
                  itemName: j.photo.item.name,
                  itemCategory: j.photo.item.category,
                  itemBrand: j.photo.item.brand,
                  itemTags: j.photo.item.tags.map(t => t.name),
                  locationPath: j.photo.item.location.path,
                  caption: j.photo.item.caption,
                  voiceNotePath: j.photo.item.voiceNotePath,
                  voiceNoteMime: j.photo.item.voiceNoteMime,
                }}
              />
            ))}
          </div>
        )}

        <div className="mt-2 text-xs text-muted-foreground space-y-1">
          <div>
            <Link href="/" className="underline">Back to search</Link>
          </div>
        </div>
      </div>
    </PageShell>
  )
}
