// tdd-guard:skip — Next.js notes index: loads data and composes links (KAR-344 Phase 2)
import Link from 'next/link'
import { redirect } from 'next/navigation'
import { createClient } from '@/lib/supabase/server'
import { NotebookPen, Plus } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { projectLabel } from '@/lib/notes/project-label'

export const metadata = {
  title: 'Projektnotizen',
}

export default async function NotesIndexPage() {
  const supabase = await createClient()
  const { data: claims } = await supabase.auth.getClaims()
  if (!claims?.claims) redirect('/login')

  const { data: notes } = await supabase
    .from('project_notes')
    .select('id, title, project_id, created_at, projects(project_code, supplier_name)')
    .order('created_at', { ascending: false })
    .limit(50)

  return (
    <div className="max-w-screen-lg mx-auto px-4 py-6 pb-24 md:pb-8 space-y-6">
      <header className="flex items-start justify-between gap-4">
        <div className="space-y-1">
          <div className="flex items-center gap-2">
            <NotebookPen size={18} className="text-primary" />
            <h1 className="font-display uppercase tracking-tight text-xl font-bold text-foreground">
              Projektnotizen
            </h1>
          </div>
          <p className="text-sm text-muted-foreground">
            Handschriftliche Notizen und Skizzen auf dem iPad, je Projekt.
          </p>
        </div>
        <Button asChild size="lg">
          <Link href="/notes/new">
            <Plus size={16} />
            Neue Notiz
          </Link>
        </Button>
      </header>

      <section className="space-y-2">
        <h2 className="text-sm font-semibold text-foreground">Zuletzt</h2>
        {!notes || notes.length === 0 ? (
          <div className="rounded-md border border-border bg-muted/30 px-4 py-6 text-center text-sm text-muted-foreground">
            Noch keine Notizen. Leg mit dem Button oben die erste an.
          </div>
        ) : (
          <ul className="space-y-1">
            {notes.map((n) => {
              const project = Array.isArray(n.projects) ? n.projects[0] : n.projects
              return (
                <li key={n.id}>
                  <Link
                    href={`/notes/${n.id}`}
                    className="flex items-center justify-between rounded-md border border-border bg-card p-3 text-sm hover:border-primary transition-colors"
                  >
                    <span className="font-medium text-foreground">{n.title || '(ohne Titel)'}</span>
                    <span className="text-xs text-muted-foreground ml-2">
                      {project ? `${projectLabel(project)} · ` : ''}
                      {new Date(n.created_at).toLocaleDateString('de-DE')}
                    </span>
                  </Link>
                </li>
              )
            })}
          </ul>
        )}
      </section>
    </div>
  )
}
