'use client'
import Link from 'next/link'
import React from 'react'

import { Media } from '@/components/Media'
import { TagBadge } from '@/components/TagBadge'
import { cn } from '@/utilities/ui'
import useClickableCard from '@/utilities/useClickableCard'

export type StoryCardData = {
  id: string | number
  title: string
  slug: string
  coverImage?: any | null
  category?: { title: string; slug: string } | null | string | number
  tags?: Array<{ id: string | number; title: string; slug: string } | string | number> | null
  publishedAt?: string | null
}

export const StoryCard: React.FC<{
  story: StoryCardData
  chapterCount?: number
  className?: string
}> = ({ story, chapterCount, className }) => {
  const { card, link } = useClickableCard({})
  const { title, slug, coverImage, category, tags, publishedAt } = story

  const categoryTitle =
    category && typeof category === 'object' && 'title' in category ? category.title : null

  const tagList = (
    tags?.filter((t): t is { id: string | number; title: string; slug: string } =>
      typeof t === 'object' && 'title' in t,
    ) ?? []
  ).slice(0, 2)

  return (
    <article
      ref={card.ref}
      className={cn(
        'group rounded-lg overflow-hidden border border-border bg-card hover:cursor-pointer hover:border-primary transition-colors',
        className,
      )}
    >
      <div className="aspect-[2/3] relative overflow-hidden bg-muted">
        {coverImage && typeof coverImage !== 'string' ? (
          <Media
            resource={coverImage}
            fill
            imgClassName="object-cover group-hover:scale-105 transition-transform duration-300"
          />
        ) : (
          <div className="absolute inset-0 bg-gradient-to-b from-muted-foreground/10 to-muted-foreground/30" />
        )}
      </div>
      <div className="p-3">
        {categoryTitle && (
          <p className="text-[10px] text-muted-foreground uppercase tracking-wide mb-1 line-clamp-1">
            {categoryTitle}
          </p>
        )}
        <h3 className="font-semibold text-sm line-clamp-2 leading-snug">
          <Link
            href={`/truyen/${slug}`}
            ref={link.ref}
            className="hover:text-primary transition-colors"
          >
            {title}
          </Link>
        </h3>
        {tagList.length > 0 && (
          <div className="flex flex-wrap gap-1 mt-2">
            {tagList.map((tag) => (
              <TagBadge key={String(tag.id)} tag={tag} size="sm" />
            ))}
          </div>
        )}
        <div className="flex items-center justify-between mt-2 text-[10px] text-muted-foreground">
          {chapterCount !== undefined && <span>{chapterCount} chương</span>}
          {publishedAt && (
            <span>{new Date(publishedAt).toLocaleDateString('vi-VN')}</span>
          )}
        </div>
      </div>
    </article>
  )
}
