import { redirect } from 'next/navigation'
import Link from 'next/link'
import { createClient } from '@/lib/supabase/server'
import { getUserSession } from '@/lib/auth/permissions'

const STATUS_LABEL: Record<string, string> = {
  draft: 'Entwurf',
  backlog: 'Backlog',
  review: 'In Review',
  promoted: 'Promoted',
  rejected: 'Abgelehnt',
  archived: 'Archiviert',
}

const CONSULTANT_ROLES = new Set(['consultant', 'admin', 'masteradmin'])

type FieldEntry = { value: unknown; block?: number }
type IntakeRow = {
  id: string
  intake_id: string
  status: string
  intake_type: string | null
  requesting_department: string | null
  priority: string | null
  supplier_id: string | null
  reviewing_consultant_id: string | null
  promoted_project_id: string | null
  created_at: string
  updated_at: string
  reviewer: { id: string; display_name: string } | null
  fields: Record<string, FieldEntry>
}

function fieldText(row: IntakeRow, key: string): string | null {
  const fv = row.fields?.[key]?.value
  if (fv == null) return null
  if (typeof fv === 'string') return fv || null
  return null
}

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

  const session = await getUserSession()
  if (session && CONSULTANT_ROLES.has(session.role)) {
    redirect('/intake/board')
  }

  // KAR-164 PR-F: list_intakes_full RPC liefert intake + fields als jsonb
  const { data: rpcResult } = await supabase.rpc('list_intakes_full', {
    p_statuses: null,
    p_limit: 100,
  })

  const intakes: Array<IntakeRow & { supplier_label: string | null }> = (
    (rpcResult as IntakeRow[] | null) ?? []
  ).map((row) => ({
    ...row,
    supplier_label: fieldText(row, 'supplier_picker'),
  }))

  return (
    <div className="min-h-screen bg-background">
      <div className="max-w-6xl mx-auto p-6 space-y-6">
        <header className="flex items-center justify-between">
          <div>
            <div className="text-xs font-condensed text-muted-foreground uppercase tracking-wide">
              Auftragseingang
            </div>
            <h1 className="font-display uppercase tracking-tight text-2xl font-bold text-foreground">Meine Aufträge</h1>
          </div>
          <Link
            href="/intake/new"
            className="px-4 py-2 text-sm font-condensed font-bold text-primary-foreground bg-primary hover:bg-primary-dark rounded-sm"
          >
            Neuer Auftrag ›
          </Link>
        </header>

        {intakes.length === 0 ? (
          <div className="bg-card border border-border rounded-md p-12 text-center">
            <p className="text-sm text-muted-foreground">
              Noch keine Aufträge angelegt. Klick auf „Neuer Auftrag“ um zu starten.
            </p>
          </div>
        ) : (
          <div className="bg-card border border-border rounded-md overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-muted text-xs font-condensed uppercase tracking-wide text-muted-foreground">
                <tr>
                  <th className="text-left px-3 py-2">Auftrags-ID</th>
                  <th className="text-left px-3 py-2">Typ</th>
                  <th className="text-left px-3 py-2">Lieferant</th>
                  <th className="text-left px-3 py-2">Abt.</th>
                  <th className="text-left px-3 py-2">Status</th>
                  <th className="text-left px-3 py-2">Priorität</th>
                  <th className="text-left px-3 py-2">Erstellt</th>
                </tr>
              </thead>
              <tbody>
                {intakes.map((it) => (
                  <tr
                    key={it.id}
                    className="border-t border-border hover:bg-state-hover"
                  >
                    <td className="px-3 py-2 font-condensed font-bold">
                      <Link href={`/intake/new?id=${it.id}`} className="text-primary hover:underline">
                        {it.intake_id}
                      </Link>
                    </td>
                    <td className="px-3 py-2 text-foreground">{it.intake_type ?? '—'}</td>
                    <td className="px-3 py-2 text-foreground">
                      {it.supplier_label ?? '—'}
                    </td>
                    <td className="px-3 py-2 font-condensed">{it.requesting_department ?? '—'}</td>
                    <td className="px-3 py-2">
                      <span className="px-2 py-0.5 text-xs font-condensed rounded-sm bg-secondary text-secondary-foreground">
                        {STATUS_LABEL[it.status] ?? it.status}
                      </span>
                    </td>
                    <td className="px-3 py-2 font-condensed">{it.priority ?? '—'}</td>
                    <td className="px-3 py-2 text-xs text-muted-foreground font-condensed">
                      {new Date(it.created_at).toLocaleDateString('de-DE')}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  )
}
