import { Link } from 'react-router'
import CoverImage from '~/components/CoverImage'

function isExternalUrl(url: string): boolean {
  try { return new URL(url).origin !== window.location.origin } catch { return true }
}

type Props = {
  authorDid: string
  rkey: string
  pubRkey?: string
  title: string
  publishedAt: string
  resolvedHandle?: string
  publicationName?: string
  coverImageCid?: string
  resolvedUrl?: string
  path?: string
  textContent?: string
  description?: string
  isDraft?: boolean
  editTo?: string
}

export default function PostCard({
  authorDid, rkey, pubRkey, title, publishedAt, resolvedHandle, publicationName,
  coverImageCid, resolvedUrl, path, textContent, description, isDraft, editTo,
}: Props) {
  const fullUrl = resolvedUrl && path ? resolvedUrl + path : null
  const href = !isDraft && fullUrl && isExternalUrl(fullUrl) ? fullUrl : null
  const innerTo = editTo ?? (fullUrl
    ? new URL(fullUrl).pathname
    : pubRkey
      ? `/${encodeURIComponent(authorDid)}/pub/${encodeURIComponent(pubRkey)}/${encodeURIComponent(rkey)}`
      : '/')

  const postLink = (children: React.ReactNode, className?: string) =>
    href
      ? <a href={href} target="_blank" rel="noopener noreferrer" className={className}>{children}</a>
      : <Link to={innerTo} className={className}>{children}</Link>

  return (
    <li className={`group rounded-lg border overflow-hidden transition-all duration-150 ${
      isDraft
        ? 'border-amber-200/70 dark:border-amber-900/40 bg-amber-50/40 dark:bg-amber-950/10'
        : 'border-stone-200 dark:border-stone-700/80 bg-white dark:bg-stone-900/40 hover:border-stone-300 dark:hover:border-stone-600 hover:shadow-md hover:-translate-y-px'
    }`}>
      <div className="flex items-stretch min-h-[5rem]">
        {coverImageCid && postLink(
          <CoverImage
            did={authorDid}
            cid={coverImageCid}
            thumbnail
            className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
          />,
          'block w-28 md:w-32 shrink-0 overflow-hidden bg-stone-100 dark:bg-stone-800',
        )}
        <div className="flex-1 px-4 py-3.5 min-w-0">
          {postLink(
            <>
              <div className="flex items-start gap-2">
                <p className="font-display text-base font-medium text-stone-900 dark:text-white line-clamp-2 leading-snug flex-1">
                  {title}
                </p>
                {isDraft && (
                  <span className="shrink-0 text-sm font-medium text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-950 border border-amber-200 dark:border-amber-800 rounded px-1.5 py-0.5 mt-px">
                    Draft
                  </span>
                )}
              </div>
              {(textContent || description) && (
                <p className="text-sm text-stone-500 dark:text-stone-400 line-clamp-2 mt-1 leading-snug">
                  {textContent || description}
                </p>
              )}
            </>,
            'block',
          )}
          <div className="flex items-center justify-between gap-2 mt-1.5">
            <p className="text-sm text-stone-400 dark:text-stone-500 truncate">
              {resolvedHandle && (
                <>
                  <Link
                    to={`/${encodeURIComponent(resolvedHandle)}`}
                    className="hover:text-stone-600 dark:hover:text-stone-300 transition-colors"
                  >
                    @{resolvedHandle}
                  </Link>
                  {publicationName && ' · '}
                </>
              )}
              {publicationName && (pubRkey
                ? <Link
                    to={`/${encodeURIComponent(resolvedHandle ?? authorDid)}/pub/${encodeURIComponent(pubRkey)}`}
                    className="hover:text-stone-600 dark:hover:text-stone-300 transition-colors"
                  >
                    {publicationName}
                  </Link>
                : publicationName
              )}
            </p>
            <p className="text-sm text-stone-400 dark:text-stone-500 shrink-0 tabular-nums">
              {new Date(publishedAt).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })}
            </p>
          </div>
        </div>
      </div>
    </li>
  )
}
