import { X, ExternalLink, Globe, BookOpen, BookOpenCheck, Trash2, Loader2 } from 'lucide-react'
import { parseISO, format } from 'date-fns'
import { useQuery } from '@tanstack/react-query'
import { api } from '../lib/api'
import { useMemo } from 'react'

interface PressArticle {
  id: number
  celebrity_id: number
  celebrity_name: string
  title: string
  url: string
  domain: string
  published_date: string
  image_url: string | null
  language: string
  country: string
  snippet: string
  article_content: string | null
  fetched_at: string
  read: number
}

// Sanitize HTML - allow safe formatting tags + media elements
function sanitizeHtml(html: string): string {
  if (!html) return ''
  const div = document.createElement('div')
  div.textContent = ''
  const temp = document.createElement('div')
  temp.innerHTML = html
  const allowedTags = new Set([
    'P', 'H2', 'H3', 'H4', 'B', 'I', 'EM', 'STRONG', 'A',
    'BLOCKQUOTE', 'UL', 'OL', 'LI', 'BR', 'FIGURE', 'FIGCAPTION',
    'IMG', 'VIDEO', 'SOURCE',
  ])
  // Attributes allowed per tag
  const allowedAttrs: Record<string, Set<string>> = {
    'A': new Set(['href']),
    'IMG': new Set(['src', 'alt']),
    'VIDEO': new Set(['src', 'poster', 'controls', 'width', 'height', 'preload']),
    'SOURCE': new Set(['src', 'type']),
  }
  function walkAndSanitize(node: Node, parent: HTMLElement) {
    if (node.nodeType === Node.TEXT_NODE) {
      parent.appendChild(document.createTextNode(node.textContent || ''))
    } else if (node.nodeType === Node.ELEMENT_NODE) {
      const el = node as HTMLElement
      if (allowedTags.has(el.tagName)) {
        const safe = document.createElement(el.tagName)
        // Copy allowed attributes for media/link tags
        const attrs = allowedAttrs[el.tagName]
        if (attrs) {
          for (const attr of attrs) {
            const val = el.getAttribute(attr)
            if (val != null) {
              // Only allow http(s) URLs for src/href/poster/srcset
              if (['src', 'href', 'poster', 'srcset'].includes(attr)) {
                if (!val.match(/^https?:\/\//) && !val.startsWith('/api/')) continue
              }
              safe.setAttribute(attr, val)
            }
          }
        }
        // Make links open in new tab
        if (el.tagName === 'A') {
          safe.setAttribute('target', '_blank')
          safe.setAttribute('rel', 'noopener noreferrer')
        }
        el.childNodes.forEach(child => walkAndSanitize(child, safe))
        parent.appendChild(safe)
      } else {
        el.childNodes.forEach(child => walkAndSanitize(child, parent))
      }
    }
  }
  temp.childNodes.forEach(child => walkAndSanitize(child, div))
  return div.innerHTML
}

interface Props {
  articleId: number
  onClose: () => void
  onMarkRead?: (id: number, read: boolean) => void
  onDelete?: (id: number) => void
}

export default function PressArticleModal({ articleId, onClose, onMarkRead, onDelete }: Props) {
  const { data, isLoading } = useQuery({
    queryKey: ['press', 'article', articleId],
    queryFn: () => api.get<{ success: boolean; article: PressArticle }>(`/press/articles/${articleId}`),
  })

  const article = data?.article

  const sanitizedContent = useMemo(() => {
    if (!article?.article_content) return ''
    // Check if content contains HTML tags
    if (/<[a-z][\s\S]*>/i.test(article.article_content)) {
      return sanitizeHtml(article.article_content)
    }
    // Plain text fallback - wrap paragraphs in <p> tags
    return article.article_content
      .split('\n\n')
      .filter(p => p.trim())
      .map(p => `<p>${p.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</p>`)
      .join('')
  }, [article?.article_content])

  const formattedDate = useMemo(() => {
    if (!article?.published_date) return null
    try {
      return format(parseISO(article.published_date), 'MMMM d, yyyy h:mm a')
    } catch {
      return article.published_date
    }
  }, [article?.published_date])

  return (
    <div
      className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black/50 backdrop-blur-sm"
      onClick={onClose}
    >
      <div
        className="card-glass-hover rounded-t-2xl sm:rounded-2xl w-full sm:max-w-4xl max-h-[90vh] sm:max-h-[85vh] overflow-hidden flex flex-col sm:mx-4"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Sticky header */}
        <div className="flex items-center justify-between px-4 sm:px-6 py-3 border-b border-slate-200 dark:border-slate-700 bg-inherit flex-shrink-0">
          {/* Drag handle for mobile */}
          <div className="w-10 h-1 bg-slate-300 dark:bg-slate-600 rounded-full sm:hidden mx-auto absolute left-1/2 -translate-x-1/2 top-1.5" />

          <div className="flex items-center gap-2 min-w-0 flex-1">
            {article && (
              <>
                <span className="px-2 py-0.5 bg-purple-500/10 text-purple-600 dark:text-purple-400 rounded text-xs font-medium flex-shrink-0">
                  {article.celebrity_name}
                </span>
                <span className="px-2 py-0.5 bg-slate-100 dark:bg-slate-800 rounded text-xs text-slate-600 dark:text-slate-400 flex-shrink-0">
                  {article.domain}
                </span>
              </>
            )}
          </div>

          <div className="flex items-center gap-1 flex-shrink-0">
            {article && onMarkRead && (
              <button
                onClick={() => onMarkRead(article.id, !article.read)}
                className="p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 text-slate-500 hover:text-slate-700 dark:hover:text-slate-200 transition-colors"
                title={article.read ? 'Mark as unread' : 'Mark as read'}
              >
                {article.read ? <BookOpenCheck className="w-4 h-4" /> : <BookOpen className="w-4 h-4" />}
              </button>
            )}
            {article && (
              <a
                href={article.url}
                target="_blank"
                rel="noopener noreferrer"
                className="p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 text-slate-500 hover:text-slate-700 dark:hover:text-slate-200 transition-colors"
                title="Open original article"
              >
                <ExternalLink className="w-4 h-4" />
              </a>
            )}
            {article && onDelete && (
              <button
                onClick={() => {
                  if (confirm('Delete this article?')) {
                    onDelete(article.id)
                    onClose()
                  }
                }}
                className="p-2 rounded-lg hover:bg-red-500/10 text-slate-500 hover:text-red-500 dark:hover:text-red-400 transition-colors"
                title="Delete article"
              >
                <Trash2 className="w-4 h-4" />
              </button>
            )}
            <button
              onClick={onClose}
              className="p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 text-slate-500 hover:text-slate-700 dark:hover:text-slate-200 transition-colors"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Scrollable content */}
        <div className="overflow-y-auto flex-1 px-4 sm:px-8 py-6">
          {isLoading ? (
            <div className="flex items-center justify-center py-20">
              <Loader2 className="w-6 h-6 animate-spin text-slate-400" />
            </div>
          ) : article ? (
            <div className="max-w-prose mx-auto">
              {/* Title */}
              <h1 className="text-xl sm:text-2xl font-bold text-slate-900 dark:text-slate-100 leading-tight">
                {article.title || 'Untitled Article'}
              </h1>

              {/* Meta */}
              <div className="flex flex-wrap items-center gap-3 mt-3 text-sm text-slate-500 dark:text-slate-400">
                {formattedDate && <span>{formattedDate}</span>}
                {article.language && article.language !== 'English' && (
                  <span className="flex items-center gap-1">
                    <Globe className="w-3.5 h-3.5" />
                    {article.language}
                  </span>
                )}
                {article.country && (
                  <span>{article.country}</span>
                )}
              </div>

              {/* Hero image */}
              {article.image_url && (
                <div className="mt-5 rounded-xl overflow-hidden bg-slate-100 dark:bg-slate-800">
                  <img
                    src={article.image_url}
                    alt=""
                    className="w-full max-h-[400px] object-cover"
                    onError={(e) => { (e.target as HTMLImageElement).style.display = 'none' }}
                  />
                </div>
              )}

              {/* Article content */}
              {sanitizedContent ? (
                <div
                  className="mt-6 article-content text-base sm:text-lg leading-relaxed text-slate-700 dark:text-slate-300
                    [&_p]:my-4 [&_p]:leading-relaxed
                    [&_h2]:text-xl [&_h2]:sm:text-2xl [&_h2]:font-bold [&_h2]:text-slate-900 dark:[&_h2]:text-slate-100 [&_h2]:mt-8 [&_h2]:mb-4
                    [&_h3]:text-lg [&_h3]:sm:text-xl [&_h3]:font-semibold [&_h3]:text-slate-900 dark:[&_h3]:text-slate-100 [&_h3]:mt-6 [&_h3]:mb-3
                    [&_h4]:text-base [&_h4]:sm:text-lg [&_h4]:font-semibold [&_h4]:text-slate-900 dark:[&_h4]:text-slate-100 [&_h4]:mt-6 [&_h4]:mb-3
                    [&_blockquote]:border-l-4 [&_blockquote]:border-blue-500 [&_blockquote]:pl-4 [&_blockquote]:my-6 [&_blockquote]:italic [&_blockquote]:text-slate-600 dark:[&_blockquote]:text-slate-400
                    [&_strong]:text-slate-900 dark:[&_strong]:text-slate-100 [&_strong]:font-semibold
                    [&_em]:italic
                    [&_ul]:list-disc [&_ul]:pl-6 [&_ul]:my-4 [&_ol]:list-decimal [&_ol]:pl-6 [&_ol]:my-4
                    [&_li]:my-2
                    [&_a]:text-blue-600 dark:[&_a]:text-blue-400 [&_a]:underline [&_a]:underline-offset-2
                    [&_img]:rounded-xl [&_img]:my-6 [&_img]:max-w-full [&_img]:h-auto
                    [&_video]:rounded-xl [&_video]:my-6 [&_video]:max-w-full [&_video]:bg-black
                    [&_figure]:my-6 [&_figcaption]:text-sm [&_figcaption]:text-slate-500 dark:[&_figcaption]:text-slate-400 [&_figcaption]:mt-2 [&_figcaption]:text-center"
                  dangerouslySetInnerHTML={{ __html: sanitizedContent }}
                />
              ) : (
                <div className="mt-6">
                  {article.snippet ? (
                    <p className="text-slate-600 dark:text-slate-400 leading-relaxed">{article.snippet}</p>
                  ) : (
                    <p className="text-slate-500 dark:text-slate-400 italic">No content available.</p>
                  )}
                  <a
                    href={article.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-2 mt-4 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors"
                  >
                    <ExternalLink className="w-4 h-4" />
                    Read on {article.domain}
                  </a>
                </div>
              )}

              {/* Source link at bottom */}
              {sanitizedContent && (
                <div className="mt-8 pt-4 border-t border-slate-200 dark:border-slate-700">
                  <a
                    href={article.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-2 text-sm text-blue-600 dark:text-blue-400 hover:underline"
                  >
                    <ExternalLink className="w-3.5 h-3.5" />
                    Read original on {article.domain}
                  </a>
                </div>
              )}
            </div>
          ) : (
            <div className="text-center py-20 text-slate-500">Article not found</div>
          )}
        </div>
      </div>
    </div>
  )
}
