import { Group, Media, Page } from '@/payload-types'
import { Container } from '@/components/Container/Container'
import { Section } from '@/components/Section/Section'
import { ImageCard } from '@/components/ImageCard/ImageCard'
import { getPhoto } from '@/utils/dto/gallery'
import styles from './imageCardsBlock.module.scss'

export type ImageCardsBlockItem = {
  title: string
  image: string | Media
  link?:
    | { relationTo: 'pages'; value: string | Page }
    | { relationTo: 'group'; value: string | Group }
    | null
  customLink?: string | null
  id?: string | null
}

type ImageCardsBlockProps = {
  items: ImageCardsBlockItem[]
}

const resolveHref = (item: ImageCardsBlockItem): string | undefined => {
  if (item.link && typeof item.link.value === 'object') {
    if (item.link.relationTo === 'pages' && item.link.value.slug) {
      return `/${item.link.value.slug}`
    }
    if (item.link.relationTo === 'group' && item.link.value.slug) {
      return `/gruppe/${item.link.value.slug}`
    }
  }
  return item.customLink ?? undefined
}

export const ImageCardsBlock = ({ items }: ImageCardsBlockProps) => {
  return (
    <Container>
      <Section padding={"small"}>
        <div className={styles.grid}>
          {items.map((item) => {
            const photo = getPhoto('thumbnail', item.image)
            if (!photo) return null

            return (
              <ImageCard
                key={item.id ?? item.title}
                src={photo.src}
                title={item.title}
                href={resolveHref(item)}
              />
            )
          })}
        </div>
      </Section>
    </Container>
  )
}
