import React, { useState } from 'react'
import { Link } from 'react-router-dom'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faLink } from '@fortawesome/free-solid-svg-icons'
import { faNewspaper, faStickyNote, faCirclePlay, faCamera, faFileLines } from '@fortawesome/free-regular-svg-icons'
import { faGlobe } from '@fortawesome/free-solid-svg-icons'
import { IndividualBookmark } from '../../types/bookmarks'
import { formatDate, renderParsedContent } from '../../utils/bookmarkUtils'
import RichContent from '../RichContent'
import { classifyUrl } from '../../utils/helpers'
import { useImageCache } from '../../hooks/useImageCache'
import { getPreviewImage, fetchOgImage } from '../../utils/imagePreview'
import { naddrEncode } from 'nostr-tools/nip19'
import { ReadingProgressBar } from '../ReadingProgressBar'

interface CardViewProps {
  bookmark: IndividualBookmark
  index: number
  hasUrls: boolean
  extractedUrls: string[]
  onSelectUrl?: (url: string, bookmark?: { id: string; kind: number; tags: string[][]; pubkey: string }) => void
  authorNpub: string
  getAuthorDisplayName: () => string
  handleReadNow: (e: React.MouseEvent<HTMLButtonElement>) => void
  articleImage?: string
  articleSummary?: string
  articleTitle?: string
  readingProgress?: number
}

export const CardView: React.FC<CardViewProps> = ({
  bookmark,
  index,
  hasUrls,
  extractedUrls,
  authorNpub,
  getAuthorDisplayName,
  handleReadNow,
  articleImage,
  articleSummary,
  articleTitle,
  readingProgress
}) => {
  const firstUrl = hasUrls ? extractedUrls[0] : null
  const firstUrlClassificationType = firstUrl ? classifyUrl(firstUrl)?.type : null
  const instantPreview = firstUrl ? getPreviewImage(firstUrl, firstUrlClassificationType || '') : null
  
  const [ogImage, setOgImage] = useState<string | null>(null)
  
  const isArticle = bookmark.kind === 30023
  const isWebBookmark = bookmark.kind === 39701
  const isNote = bookmark.kind === 1
  
  // Extract title from tags for regular bookmarks (not just articles)
  const bookmarkTitle = bookmark.tags.find(t => t[0] === 'title')?.[1]
  
  // Get content type icon based on bookmark kind and URL classification
  const getContentTypeIcon = () => {
    if (isArticle) return faNewspaper // Nostr-native article
    
    // For web bookmarks, classify the URL to determine icon
    if (isWebBookmark && firstUrlClassificationType) {
      switch (firstUrlClassificationType) {
        case 'youtube':
        case 'video':
          return faCirclePlay
        case 'image':
          return faCamera
        case 'article':
          return faFileLines
        default:
          return faGlobe
      }
    }
    
    // For notes, use sticky note icon
    if (isNote) return faStickyNote
    
    // Default fallback
    return faLink
  }
  
  
  // Determine which image to use (article image, instant preview, or OG image)
  const previewImage = articleImage || instantPreview || ogImage
  const cachedImage = useImageCache(previewImage || undefined)
  
  // Fetch OG image if we don't have any other image
  React.useEffect(() => {
    if (firstUrl && !articleImage && !instantPreview && !ogImage) {
      fetchOgImage(firstUrl).then(setOgImage)
    }
  }, [firstUrl, articleImage, instantPreview, ogImage])


  const triggerOpen = () => handleReadNow({ preventDefault: () => {} } as React.MouseEvent<HTMLButtonElement>)

  const handleKeyDown: React.KeyboardEventHandler<HTMLDivElement> = (e) => {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault()
      triggerOpen()
    }
  }

  // Get internal route for the bookmark
  const getInternalRoute = (): string | null => {
    if (bookmark.kind === 30023) {
      // Nostr-native article - use /a/ route
      const dTag = bookmark.tags.find(t => t[0] === 'd')?.[1]
      if (dTag) {
        const naddr = naddrEncode({
          kind: bookmark.kind,
          pubkey: bookmark.pubkey,
          identifier: dTag
        })
        return `/a/${naddr}`
      }
    } else if (bookmark.kind === 1) {
      // Note - use /e/ route
      return `/e/${bookmark.id}`
    } else if (firstUrl) {
      // External URL - use /r/ route
      return `/r/${encodeURIComponent(firstUrl)}`
    }
    return null
  }

  return (
    <div 
      key={`${bookmark.id}-${index}`}
      className={`individual-bookmark card-view ${bookmark.isPrivate ? 'private-bookmark' : ''}`}
      onClick={triggerOpen}
      role="button"
      tabIndex={0}
      onKeyDown={handleKeyDown}
    >
      <div className="card-layout">
        <div className="card-content">
          <div className="card-content-header">
            {(cachedImage || firstUrl) && (
              <div 
                className="card-thumbnail"
                style={cachedImage ? { backgroundImage: `url(${cachedImage})` } : undefined}
                onClick={() => handleReadNow({ preventDefault: () => {} } as React.MouseEvent<HTMLButtonElement>)}
              >
            {!cachedImage && firstUrl && (
              <div className="thumbnail-placeholder">
                <FontAwesomeIcon icon={getContentTypeIcon()} />
              </div>
            )}
              </div>
            )}
            <div className="card-text-content">
        <div className="bookmark-header">
        </div>
        
        {/* Display title for articles or bookmarks with titles */}
        {(articleTitle || bookmarkTitle) && (
          <h3 className="bookmark-title">
            <RichContent content={articleTitle || bookmarkTitle || ''} className="" />
          </h3>
        )}
        
        {isArticle && articleSummary ? (
          <RichContent content={articleSummary} className="bookmark-content article-summary" />
        ) : bookmark.parsedContent ? (
          <div className="bookmark-content">
            {renderParsedContent(bookmark.parsedContent)}
          </div>
        ) : bookmark.content && (
          <RichContent content={bookmark.content} className="bookmark-content" />
        )}
        
            </div>
          </div>
        </div>
        
        {/* Reading progress indicator as separator - always shown for all bookmark types */}
        <ReadingProgressBar 
          readingProgress={readingProgress}
          height={1}
          marginTop="0.125rem"
          marginBottom="0.125rem"
        />
        
        <div className="bookmark-footer">
          <div className="bookmark-meta-minimal">
            <Link
              to={`/p/${authorNpub}`}
              className="author-link-minimal"
              title="Open author profile"
              onClick={(e) => e.stopPropagation()}
            >
              {getAuthorDisplayName()}
            </Link>
          </div>
          <div className="bookmark-footer-right">
            {getInternalRoute() ? (
              <Link
                to={getInternalRoute()!}
                className="bookmark-date-link"
                title="Open in app"
                onClick={(e) => e.stopPropagation()}
              >
                {formatDate(bookmark.created_at ?? bookmark.listUpdatedAt)}
              </Link>
            ) : (
              <span className="bookmark-date">{formatDate(bookmark.created_at ?? bookmark.listUpdatedAt)}</span>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

