import Link from 'next/link'
import { db } from '@/lib/db'
import { Card, Caveat, Label } from '@/components/ui'
import { SPIRITUAL_CADENCE_DAYS } from '@/lib/cadence'
import { TopicList, AddTopic } from './controls'

export default async function TopicsPage() {
  const constructs = await db.construct.findMany({
    where: { subject: 'SPIRITUAL' },
    orderBy: { sortOrder: 'asc' },
  })
  const topics = await db.topic.findMany({
    orderBy: [{ active: 'desc' }, { sortOrder: 'asc' }],
    include: { construct: true },
  })

  return (
    <div className="space-y-6">
      <div>
        <Link href="/parent" className="text-xs text-[var(--color-muted)] hover:underline">
          &larr; Back
        </Link>
        <h1 className="mt-2 text-xl font-semibold">Spiritual topics</h1>
        <p className="text-sm text-[var(--color-muted)]">
          What the boys should be covering. The generator draws only from the
          active items here, favouring whatever has gone longest without being
          covered. Spiritual sets run on their own clock &mdash; currently every{' '}
          {SPIRITUAL_CADENCE_DAYS} days.
        </p>
      </div>

      <Caveat>
        Questions are written <strong>about</strong> these concepts, from the
        model&rsquo;s own knowledge of them. Nothing is copied from the ministry
        books &mdash; they&rsquo;re in copyright, and the project holds the same line
        it holds on secure test items. Scripture is quoted from a public-domain
        translation. Scoring stops at whether he knows it and understands it;
        nothing measures his walk.
      </Caveat>

      <AddTopic constructs={constructs.map((c) => ({ code: c.code, label: c.label }))} />

      {topics.length === 0 ? (
        <Card>
          <p className="text-sm text-[var(--color-muted)]">
            Nothing here yet. Until you add something, a spiritual set will be
            broad and gentle rather than aimed at what you&rsquo;re actually teaching.
          </p>
        </Card>
      ) : (
        <TopicList
          topics={topics.map((t) => ({
            id: t.id,
            label: t.label,
            notes: t.notes,
            active: t.active,
            constructLabel: t.construct.label,
            lastCovered: t.lastCoveredAt ? t.lastCoveredAt.toLocaleDateString() : null,
          }))}
        />
      )}
    </div>
  )
}
