import { prisma } from '@innungsapp/shared'
import { auth, getSanitizedHeaders } from '@/lib/auth'
import { headers } from 'next/headers'
import { redirect } from 'next/navigation'
import { format } from 'date-fns'
import { de } from 'date-fns/locale'
import { DeactivateButton } from './DeactivateButton'
import Link from 'next/link'

export default async function StellenPage() {
  const sanitizedHeaders = await getSanitizedHeaders()
  const session = await auth.api.getSession({ headers: sanitizedHeaders })
  if (!session?.user) redirect('/login')
  const userRole = await prisma.userRole.findFirst({
    where: { userId: session.user.id, role: 'admin' },
  })
  if (!userRole) redirect('/dashboard')

  const stellen = await prisma.stelle.findMany({
    where: { orgId: userRole.orgId },
    include: { member: { select: { name: true, betrieb: true } } },
    orderBy: [{ aktiv: 'desc' }, { createdAt: 'desc' }],
  })

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Lehrlingsbörse</h1>
          <p className="text-gray-500 mt-1">
            {stellen.filter((s) => s.aktiv).length} aktive Angebote
          </p>
        </div>
        <Link
          href="/dashboard/stellen/neu"
          className="bg-brand-500 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-brand-600 transition-colors"
        >
          + Stelle anlegen
        </Link>
      </div>

      <div className="bg-white rounded-lg border overflow-hidden">
        <table className="w-full data-table">
          <thead>
            <tr>
              <th>Betrieb</th>
              <th>Sparte</th>
              <th>Stellen</th>
              <th>Lehrjahr</th>
              <th>Vergütung</th>
              <th>Eingestellt</th>
              <th>Status</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {stellen.map((s) => (
              <tr key={s.id} className={!s.aktiv ? 'opacity-50' : ''}>
                <td>
                  <p className="font-medium text-gray-900">{s.member.betrieb}</p>
                  <p className="text-xs text-gray-500">{s.member.name}</p>
                </td>
                <td>{s.sparte}</td>
                <td className="text-center">{s.stellenAnz}</td>
                <td>{s.lehrjahr ?? '—'}</td>
                <td>{s.verguetung ?? '—'}</td>
                <td>{format(s.createdAt, 'dd.MM.yyyy', { locale: de })}</td>
                <td>
                  <span
                    className={`px-2 py-0.5 rounded-full text-xs font-medium ${s.aktiv ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}
                  >
                    {s.aktiv ? 'Aktiv' : 'Inaktiv'}
                  </span>
                </td>
                <td>
                  {s.aktiv && <DeactivateButton id={s.id} />}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {stellen.length === 0 && (
          <div className="text-center py-8 text-gray-500">Noch keine Stellenangebote</div>
        )}
      </div>
    </div>
  )
}
