'use client';

import Link from 'next/link';
import React from 'react';

import { Media } from '@/components/Media';
import type { Post } from '@/payload-types';
import { cn } from '@/utilities/ui';
import useClickableCard from '@/utilities/useClickableCard';

export type CardPostData = Pick<
  Post,
  'slug' | 'categories' | 'meta' | 'title' | 'postType' | 'updatedAt'
>;

export const Card: React.FC<{
  alignItems?: 'center';
  className?: string;
  doc?: CardPostData;
  showCategories?: boolean;
  showImage?: boolean;
  title?: string;
}> = (props) => {
  const { card, link } = useClickableCard({});
  const { className, doc, showCategories, showImage = true, title: titleFromProps } = props;

  const { slug, categories, meta, title, postType, updatedAt } = doc || {};
  const { description, image: metaImage } = meta || {};

  const hasCategories = categories && Array.isArray(categories) && categories.length > 0;
  const titleToUse = titleFromProps || title;
  const sanitizedDescription = description?.replace(/\s/g, ' '); // replace non-breaking space with white space

  // Determine URL based on postType: 'blog' posts go to /blog, 'hub' posts go to /hub
  const basePath = postType === 'hub' ? 'hub' : 'blog';
  const href = `/${basePath}/${slug}`;

  // Format date
  const formattedDate = updatedAt
    ? new Date(updatedAt).toLocaleDateString('en-US', {
        month: 'long',
        day: 'numeric',
        year: 'numeric',
      })
    : null;

  return (
    <article className={cn('group flex flex-col hover:cursor-pointer', className)} ref={card.ref}>
      {/* Image */}
      {showImage && (
        <Link href={href} ref={link.ref} className='mb-4 block'>
          <div className='relative aspect-[16/9] w-full overflow-hidden bg-gray-100'>
            {metaImage && typeof metaImage !== 'string' && (
              <Media resource={metaImage} size='33vw' className='h-full w-full object-cover' />
            )}
          </div>
        </Link>
      )}

      {/* Content */}
      <div className='flex flex-1 flex-col'>
        {/* Date */}
        {formattedDate && (
          <time className='mb-3 text-sm text-gray-500' dateTime={updatedAt || undefined}>
            {formattedDate}
          </time>
        )}

        {/* Title */}
        {titleToUse && (
          <h3 className='leading-tighter mb-3 font-serif text-3xl font-thin tracking-tight'>
            <Link href={href} className='transition-opacity hover:opacity-80'>
              {titleToUse}
            </Link>
          </h3>
        )}

        {/* Description */}
        {sanitizedDescription && (
          <p className='mb-4 font-serif text-base font-thin leading-tight tracking-tight text-gray-700'>
            {sanitizedDescription}
          </p>
        )}

        {/* Category Badges */}
        {showCategories && hasCategories && (
          <div className='mt-auto flex flex-wrap gap-2'>
            {categories?.map((category, index) => {
              if (typeof category === 'object') {
                const { title: categoryTitle } = category;
                const displayTitle = categoryTitle || 'Untitled';

                return (
                  <span
                    key={index}
                    className='inline-flex items-center rounded-full border border-gray-300 bg-white px-3 py-1 text-sm font-medium text-gray-700'
                  >
                    {displayTitle}
                  </span>
                );
              }
              return null;
            })}
          </div>
        )}
      </div>
    </article>
  );
};
