import { cookies } from 'next/headers'
import { getIronSession } from 'iron-session'
import { SessionData, sessionOptions } from '@/lib/session'
import { prisma } from '@/lib/prisma'
import { productAccessFilter } from '@/lib/product-access'
import Link from 'next/link'
import { ProductList } from '@/components/dashboard/product-list'
import { NewProductButton } from '@/components/dashboard/new-product-button'

interface Props {
  searchParams: Promise<{ archived?: string }>
}

export default async function DashboardPage({ searchParams }: Props) {
  const session = await getIronSession<SessionData>(await cookies(), sessionOptions)
  const { archived } = await searchParams
  const showArchived = archived === '1'

  const [products, user] = await Promise.all([
    prisma.product.findMany({
      where: { archived: showArchived, ...productAccessFilter(session.userId) },
      orderBy: { created_at: 'desc' },
    }),
    session.userId
      ? prisma.user.findUnique({ where: { id: session.userId }, select: { active_product_id: true } })
      : null,
  ])

  return (
    <div className="p-6 max-w-4xl mx-auto w-full">
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <h1 className="text-xl font-medium text-foreground">
            {showArchived ? 'Gearchiveerde producten' : 'Mijn Producten'}
          </h1>
          {showArchived ? (
            <Link href="/dashboard" className="text-xs text-primary hover:underline">
              ← Actief
            </Link>
          ) : (
            <Link href="/dashboard?archived=1" className="text-xs text-muted-foreground hover:text-foreground">
              Toon gearchiveerd
            </Link>
          )}
        </div>
        {!session.isDemo && !showArchived && <NewProductButton />}
      </div>

      <ProductList
        products={products}
        isDemo={session.isDemo ?? false}
        showArchived={showArchived}
        activeProductId={user?.active_product_id ?? null}
      />
    </div>
  )
}
