"use client"

import { formatDistanceToNow, format } from "date-fns"
import { classNames } from "@/lib/utilities"
import { useUserInterfaceStore } from "@/lib/stores/user-interface-store"
import type { TimelineEntry } from "@/lib/types/timeline"
import type { VirtualItem } from "@tanstack/react-virtual"

function getEntryFaviconUrl(entryUrl: string): string | null {
  try {
    const hostname = new URL(entryUrl).hostname
    return `https://www.google.com/s2/favicons?domain=${hostname}&sz=16`
  } catch {
    return null
  }
}

interface EntryListItemProperties {
  entry: TimelineEntry
  isSelected: boolean
  isFocused: boolean
  viewMode: "compact" | "comfortable" | "expanded"
  onSelect: () => void
  measureReference: (element: HTMLElement | null) => void
  virtualItem: VirtualItem
}

function stripHtmlTags(html: string): string {
  return html
    .replace(/<[^>]*>/g, "")
    .replace(/&#(\d+);/g, (_, code) => String.fromCharCode(Number(code)))
    .replace(/&#x([0-9a-fA-F]+);/g, (_, code) => String.fromCharCode(parseInt(code, 16)))
    .replace(/&amp;/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"')
    .replace(/&apos;/g, "'")
    .replace(/&nbsp;/g, " ")
    .trim()
}

export function EntryListItem({
  entry,
  isSelected,
  isFocused,
  viewMode,
  onSelect,
  measureReference,
  virtualItem,
}: EntryListItemProperties) {
  const timeDisplayFormat = useUserInterfaceStore(
    (state) => state.timeDisplayFormat
  )
  const showEntryImages = useUserInterfaceStore(
    (state) => state.showEntryImages
  )
  const showEntryFavicons = useUserInterfaceStore(
    (state) => state.showEntryFavicons
  )

  const faviconUrl = showEntryFavicons ? getEntryFaviconUrl(entry.entryUrl) : null

  const formattedTimestamp = entry.publishedAt
    ? timeDisplayFormat === "absolute"
      ? format(new Date(entry.publishedAt), "MMM d, h:mm a")
      : formatDistanceToNow(new Date(entry.publishedAt), { addSuffix: true })
    : ""

  const displayTitle = entry.customTitle ?? entry.feedTitle

  return (
    <button
      type="button"
      ref={measureReference}
      data-index={virtualItem.index}
      onClick={onSelect}
      className={classNames(
        "absolute left-0 top-0 w-full cursor-pointer border-b border-border bg-transparent px-4 text-left font-[inherit] text-[inherit] transition-colors",
        isSelected
          ? "bg-background-tertiary"
          : isFocused
            ? "bg-background-secondary"
            : "hover:bg-background-secondary",
        isFocused && !isSelected ? "border-l-2 border-l-text-dim" : "",
        entry.isRead ? "opacity-60" : ""
      )}
      style={{ transform: `translateY(${virtualItem.start}px)` }}
    >
      {viewMode === "compact" && (
        <div className="flex items-center gap-2 py-2.5">
          {faviconUrl && (
            <img src={faviconUrl} alt="" width={16} height={16} className="shrink-0" loading="lazy" />
          )}
          <span className="shrink-0 text-text-dim">{displayTitle}</span>
          {entry.enclosureUrl && (
            <span className="shrink-0 text-text-dim" title="podcast episode">&#9835;</span>
          )}
          <span className="min-w-0 flex-1 truncate text-text-primary">
            {entry.entryTitle}
          </span>
          <span className="shrink-0 text-text-dim">{formattedTimestamp}</span>
        </div>
      )}

      {viewMode === "comfortable" && (
        <div className="py-2.5">
          <div className="truncate text-text-primary">{entry.entryTitle}</div>
          <div className="mt-0.5 flex items-center gap-2 text-text-dim">
            {faviconUrl && (
              <img src={faviconUrl} alt="" width={16} height={16} className="shrink-0" loading="lazy" />
            )}
            <span>{displayTitle}</span>
            {entry.enclosureUrl && (
              <span title="podcast episode">&#9835;</span>
            )}
            {entry.author && (
              <>
                <span>&middot;</span>
                <span>{entry.author}</span>
              </>
            )}
            <span>&middot;</span>
            <span>{formattedTimestamp}</span>
          </div>
        </div>
      )}

      {viewMode === "expanded" && (
        <div className="flex gap-3 py-3">
          <div className="min-w-0 flex-1">
            <div className="truncate text-text-primary">
              {entry.entryTitle}
            </div>
            {entry.summary && (
              <p className="mt-1 line-clamp-2 text-text-secondary">
                {stripHtmlTags(entry.summary)}
              </p>
            )}
            <div className="mt-1 flex items-center gap-2 text-text-dim">
              {faviconUrl && (
                <img src={faviconUrl} alt="" width={16} height={16} className="shrink-0" loading="lazy" />
              )}
              <span>{displayTitle}</span>
              {entry.enclosureUrl && (
                <span title="podcast episode">&#9835;</span>
              )}
              {entry.author && (
                <>
                  <span>&middot;</span>
                  <span>{entry.author}</span>
                </>
              )}
              <span>&middot;</span>
              <span>{formattedTimestamp}</span>
            </div>
          </div>
          {showEntryImages && entry.imageUrl && (
            <img
              src={entry.imageUrl}
              alt=""
              className="hidden h-16 w-16 shrink-0 object-cover sm:block"
              loading="lazy"
            />
          )}
        </div>
      )}
    </button>
  )
}
