import Link from 'next/link'
import { Search } from '@/payload-types'
import { Section } from '@/components/Section/Section'
import { Container } from '@/components/Container/Container'
import { PageHeader } from '@/compositions/PageHeader/PageHeader'
import { getSearchResultUrl } from '@/utils/getSearchResultUrl'
import styles from './styles.module.scss'

const RELATION_LABELS: Record<Search['doc']['relationTo'], string> = {
  pages: 'Seite',
  blog: 'Nachricht',
  parish: 'Gemeinde',
  event: 'Veranstaltung',
  group: 'Gruppe',
}

type SearchPageProps = {
  query: string
  results: Search[]
}

export const SearchPage = ({ query, results }: SearchPageProps) => {
  const linkedResults = results
    .map((result) => ({ result, href: getSearchResultUrl(result.doc) }))
    .filter((r): r is { result: Search; href: string } => r.href !== null)

  const description = query
    ? `Suchergebnisse für „${query}"`
    : 'Bitte geben Sie einen Suchbegriff ein.'

  return (
    <>
      <PageHeader title="Suche" description={description} />

      <Section padding="small">
        <Container>
          {query && linkedResults.length === 0 && (
            <p className={styles.empty}>Keine Ergebnisse für „{query}“.</p>
          )}

          {linkedResults.length > 0 && (
            <ul className={styles.results}>
              {linkedResults.map(({ result, href }) => (
                <li key={result.id} className={styles.result}>
                  <Link href={href} className={styles.resultLink}>
                    <span className={styles.resultTitle}>{result.title}</span>
                    <span className={styles.resultType}>
                      {RELATION_LABELS[result.doc.relationTo]}
                    </span>
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </Container>
      </Section>
    </>
  )
}
