import { ImageWrapper } from '@/components/content/ImageWrapper'
import { PostMeta } from '@/types/Post.type'
import Link from 'next/link'
import { dateFormatter } from '@/utils/time'
import { cn } from '@/utils/cn'

type PostProps = {
  post: PostMeta
  isLatest?: boolean
  showImageSlot?: boolean
}

export function Post({ post, isLatest, showImageSlot }: PostProps) {
  const { title, description, category, date, coverImage, coverImageAlt, readingTimeText, slug } =
    post

  if (!title || !description || !date) {
    return null
  }

  const publishedAt = new Date(date)

  return (
    <article className={cn('flex flex-col gap-4', isLatest && 'items-center md:flex-row')}>
      {((isLatest && coverImage) || showImageSlot) && (
        <div
          className={cn(
            isLatest && coverImage ? 'flex-1 w-full' : 'h-60',
            !coverImage && 'hidden md:block',
          )}
        >
          {coverImage && <ImageWrapper src={coverImage} alt={coverImageAlt ?? title} isListing />}
        </div>
      )}
      <div className={cn('flex flex-col gap-1 w-full', isLatest && 'flex-1')}>
        {isLatest && <span className="text-xs font-mono text-accent">Latest post</span>}
        {category && (
          <div className="font-mono text-xs flex gap-1 flex-wrap text-fg-dim mt-1 categories">
            <span>{category}</span>
          </div>
        )}
        <h2 className="text-2xl font-bold">
          <Link href={`/posts/${slug}`} className="hover:underline">
            {title}
          </Link>
        </h2>
        <p className="text-fg-dim text-sm">{description}</p>
        <div className="flex gap-2 items-center text-fg-dim text-xs font-mono mt-1">
          <time dateTime={publishedAt.toISOString()}>{dateFormatter.format(publishedAt)}</time>
          <span>&middot;</span>
          <span>{readingTimeText}</span>
        </div>
      </div>
    </article>
  )
}
