import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useState, useEffect, useRef } from 'react'
import { Link } from 'react-router-dom'
import { useBreadcrumb } from '../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../config/breadcrumbConfig'
import {
  Newspaper, ExternalLink, Loader2, RefreshCcw, Trash2,
  BookOpen, BookOpenCheck, Globe, Settings
} from 'lucide-react'
import { api } from '../lib/api'
import { notificationManager } from '../lib/notificationManager'
import { parseISO, formatDistanceToNow } from 'date-fns'
import { FilterBar } from '../components/FilterPopover'
import PressArticleModal from '../components/PressArticleModal'

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
}

interface PressStats {
  total: number
  unread: number
  by_celebrity: Array<{ id: number; name: string; count: number }>
  by_domain: Array<{ domain: string; count: number }>
}

export default function Press() {
  useBreadcrumb(breadcrumbConfig['/press'])

  const queryClient = useQueryClient()
  const [modalArticleId, setModalArticleId] = useState<number | null>(null)
  const [celebrityFilter, setCelebrityFilter] = useState<string>('all')
  const [domainFilter, setDomainFilter] = useState<string>('all')
  const [readFilter, setReadFilter] = useState<string>('unread')
  const [searchText, setSearchText] = useState<string>('')
  const [page, setPage] = useState(1)

  // Fetch stats
  const { data: statsData } = useQuery({
    queryKey: ['press', 'stats'],
    queryFn: () => api.get<{ success: boolean; stats: PressStats }>('/press/stats'),
    refetchInterval: 30000,
  })

  // Fetch articles
  const { data: articlesData, isLoading } = useQuery({
    queryKey: ['press', 'articles', celebrityFilter, domainFilter, searchText, readFilter, page],
    queryFn: () => {
      const params = new URLSearchParams()
      if (celebrityFilter !== 'all') params.set('celebrity_id', celebrityFilter)
      if (domainFilter !== 'all') params.set('domain', domainFilter)
      if (searchText) params.set('search', searchText)
      if (readFilter === 'unread') params.set('read', 'false')
      else if (readFilter === 'read') params.set('read', 'true')
      params.set('page', String(page))
      params.set('per_page', '50')
      const qs = params.toString()
      return api.get<{
        success: boolean
        articles: PressArticle[]
        total: number
        page: number
        pages: number
      }>(`/press/articles${qs ? '?' + qs : ''}`)
    },
    refetchInterval: 60000,
  })

  // Fetch status
  const { data: fetchStatus } = useQuery({
    queryKey: ['press', 'fetch', 'status'],
    queryFn: () => api.get<{ success: boolean; is_running: boolean }>('/press/fetch/status'),
    refetchInterval: 5000,
  })

  // Auto-refresh articles when background fetch completes
  const prevRunning = useRef(false)
  useEffect(() => {
    const running = fetchStatus?.is_running ?? false
    if (prevRunning.current && !running) {
      // Fetch just completed - refresh everything
      queryClient.invalidateQueries({ queryKey: ['press'] })
    }
    prevRunning.current = running
  }, [fetchStatus?.is_running, queryClient])

  // Mutations
  const fetchMutation = useMutation({
    mutationFn: () => api.post<{ success: boolean; message: string }>('/press/fetch', {}),
    onSuccess: (data) => {
      notificationManager.success('Press', data.message || 'Fetch started')
      queryClient.invalidateQueries({ queryKey: ['press'] })
    },
    onError: () => notificationManager.error('Press', 'Failed to start fetch'),
  })

  const markReadMutation = useMutation({
    mutationFn: ({ id, read }: { id: number; read: boolean }) =>
      api.patch<{ success: boolean }>(`/press/articles/${id}/read`, { read }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['press'] })
    },
  })

  const markAllReadMutation = useMutation({
    mutationFn: () => api.post<{ success: boolean; message: string; count: number }>('/press/articles/mark-all-read', {}),
    onSuccess: (data) => {
      notificationManager.success('Press', data.message || 'All articles marked as read')
      queryClient.invalidateQueries({ queryKey: ['press'] })
    },
    onError: () => notificationManager.error('Press', 'Failed to mark all as read'),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: number) =>
      api.delete<{ success: boolean }>(`/press/articles/${id}`),
    onSuccess: () => {
      notificationManager.success('Press', 'Article deleted')
      queryClient.invalidateQueries({ queryKey: ['press'] })
    },
  })

  const stats = statsData?.stats
  const articles = articlesData?.articles || []
  const totalPages = articlesData?.pages || 1
  const totalCount = articlesData?.total || 0
  const isFetching = fetchStatus?.is_running || false

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
            <Newspaper className="w-6 h-6 sm:w-8 sm:h-8 text-blue-500" />
            Press
          </h1>
          <p className="text-sm sm:text-base text-slate-600 dark:text-slate-400 mt-1">
            News articles about your tracked celebrities
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Link
            to="/config?tab=press"
            className="px-3 sm:px-4 py-2.5 bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-300 hover:bg-slate-300 dark:hover:bg-slate-600 rounded-lg text-sm font-medium transition-colors flex items-center gap-2 min-h-[44px]"
            title="Configure in Settings"
          >
            <Settings className="w-4 h-4" />
            <span className="hidden sm:inline">Settings</span>
          </Link>
          {stats && stats.unread > 0 && (
            <button
              onClick={() => markAllReadMutation.mutate()}
              disabled={markAllReadMutation.isPending}
              className="px-3 sm:px-4 py-2.5 bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-300 hover:bg-slate-300 dark:hover:bg-slate-600 rounded-lg text-sm font-medium transition-colors flex items-center gap-2 min-h-[44px]"
            >
              <BookOpenCheck className="w-4 h-4" />
              <span className="hidden sm:inline">{markAllReadMutation.isPending ? 'Marking...' : 'Mark All Read'}</span>
            </button>
          )}
          <button
            onClick={() => fetchMutation.mutate()}
            disabled={isFetching || fetchMutation.isPending}
            className="flex-1 sm:flex-initial px-3 sm:px-4 py-2.5 bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-lg font-medium text-sm flex items-center justify-center gap-2 hover:from-blue-700 hover:to-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all min-h-[44px]"
          >
            {isFetching ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <RefreshCcw className="w-4 h-4" />
            )}
            <span className="hidden sm:inline">{isFetching ? 'Fetching...' : 'Fetch Articles'}</span>
            <span className="sm:hidden">{isFetching ? '...' : 'Fetch'}</span>
          </button>
        </div>
      </div>

      {/* Filters */}
      <div className="card-glass-hover rounded-xl p-4 relative z-30">
        <FilterBar
          searchValue={searchText}
          onSearchChange={(v) => { setSearchText(v); setPage(1) }}
          searchPlaceholder="Search articles..."
          filterSections={[
            {
              id: 'celebrity',
              label: 'Celebrity',
              type: 'select',
              options: [
                { value: 'all', label: 'All Celebrities' },
                ...(stats?.by_celebrity.map(c => ({ value: String(c.id), label: `${c.name} (${c.count})` })) || [])
              ],
              value: celebrityFilter,
              onChange: (v) => { setCelebrityFilter(v as string); setPage(1) }
            },
            {
              id: 'domain',
              label: 'Source',
              type: 'select',
              options: [
                { value: 'all', label: 'All Sources' },
                ...(stats?.by_domain.map(d => ({ value: d.domain, label: `${d.domain} (${d.count})` })) || [])
              ],
              value: domainFilter,
              onChange: (v) => { setDomainFilter(v as string); setPage(1) }
            },
            {
              id: 'read',
              label: 'Status',
              type: 'select',
              options: [
                { value: 'all', label: 'All Articles' },
                { value: 'unread', label: 'Unread Only' },
                { value: 'read', label: 'Read Only' }
              ],
              value: readFilter,
              onChange: (v) => { setReadFilter(v as string); setPage(1) }
            }
          ]}
          activeFilters={[
            ...(celebrityFilter !== 'all' ? [{
              id: 'celebrity',
              label: 'Celebrity',
              value: celebrityFilter,
              displayValue: stats?.by_celebrity.find(c => String(c.id) === celebrityFilter)?.name || celebrityFilter,
              onRemove: () => { setCelebrityFilter('all'); setPage(1) }
            }] : []),
            ...(domainFilter !== 'all' ? [{
              id: 'domain',
              label: 'Source',
              value: domainFilter,
              displayValue: domainFilter,
              onRemove: () => { setDomainFilter('all'); setPage(1) }
            }] : []),
            ...(readFilter !== 'all' ? [{
              id: 'read',
              label: 'Status',
              value: readFilter,
              displayValue: readFilter === 'unread' ? 'Unread Only' : 'Read Only',
              onRemove: () => { setReadFilter('all'); setPage(1) }
            }] : [])
          ]}
          onClearAll={() => {
            setSearchText('')
            setCelebrityFilter('all')
            setDomainFilter('all')
            setReadFilter('all')
            setPage(1)
          }}
          totalCount={totalCount}
          countLabel="articles"
        />
      </div>

      {/* Articles List */}
      {isLoading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-6 h-6 animate-spin text-slate-400" />
        </div>
      ) : articles.length === 0 ? (
        <div className="text-center py-12 text-slate-500 dark:text-slate-400">
          <Newspaper className="w-12 h-12 mx-auto mb-3 opacity-50" />
          <p className="text-lg">No articles found</p>
          <p className="text-sm mt-1">Click "Fetch Articles" to search for news about your tracked celebrities</p>
        </div>
      ) : (
        <div className="space-y-3">
          {articles.map((article) => (
              <div
                key={article.id}
                className={`card-glass-hover rounded-xl overflow-hidden transition-colors cursor-pointer ${
                  article.read ? '' : 'ring-1 ring-blue-500/30'
                }`}
                onClick={() => {
                  setModalArticleId(article.id)
                  if (!article.read) {
                    markReadMutation.mutate({ id: article.id, read: true })
                  }
                }}
              >
                <div className="flex gap-4 p-4">
                  {/* Thumbnail */}
                  {article.image_url && (
                    <div className="flex-shrink-0 w-24 h-24 rounded-lg overflow-hidden bg-slate-100 dark:bg-slate-800">
                      <img
                        src={article.image_url}
                        alt=""
                        className="w-full h-full object-cover"
                        onError={(e) => { (e.target as HTMLImageElement).style.display = 'none' }}
                      />
                    </div>
                  )}

                  {/* Content */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-start justify-between gap-2">
                      <div className="flex-1 min-w-0">
                        <span className="text-slate-900 dark:text-slate-100 hover:text-blue-600 dark:hover:text-blue-400 font-medium line-clamp-2 transition-colors">
                          {article.title || 'Untitled Article'}
                        </span>
                        <div className="flex items-center gap-2 mt-1.5 text-xs text-slate-500 dark:text-slate-400">
                          <span className="px-1.5 py-0.5 bg-slate-100 dark:bg-slate-800 rounded text-slate-600 dark:text-slate-400">
                            {article.domain}
                          </span>
                          <span className="px-1.5 py-0.5 bg-purple-500/10 text-purple-600 dark:text-purple-400 rounded">
                            {article.celebrity_name}
                          </span>
                          {article.published_date && (
                            <span title={article.published_date}>
                              {(() => {
                                try {
                                  return formatDistanceToNow(parseISO(article.published_date), { addSuffix: true })
                                } catch {
                                  return article.published_date
                                }
                              })()}
                            </span>
                          )}
                          {article.language && article.language !== 'English' && (
                            <span className="flex items-center gap-1">
                              <Globe className="w-3 h-3" />
                              {article.language}
                            </span>
                          )}
                        </div>
                      </div>

                      {/* Actions */}
                      <div className="flex items-center gap-1 flex-shrink-0" onClick={(e) => e.stopPropagation()}>
                        <button
                          onClick={() => markReadMutation.mutate({ id: article.id, read: !article.read })}
                          className="p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 text-slate-400 dark: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>
                        <a
                          href={article.url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 text-slate-400 dark:text-slate-500 hover:text-slate-700 dark:hover:text-slate-200 transition-colors"
                          title="Open original"
                        >
                          <ExternalLink className="w-4 h-4" />
                        </a>
                        <button
                          onClick={() => {
                            if (confirm('Delete this article?')) {
                              deleteMutation.mutate(article.id)
                            }
                          }}
                          className="p-1.5 rounded-lg hover:bg-red-500/10 text-slate-400 dark:text-slate-500 hover:text-red-500 dark:hover:text-red-400 transition-colors"
                          title="Delete"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </div>

                    {/* Snippet */}
                    {article.snippet && (
                      <p className="text-sm text-slate-500 dark:text-slate-400 mt-2 line-clamp-2">{article.snippet}</p>
                    )}
                  </div>
                </div>
              </div>
          ))}
        </div>
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-2">
          <button
            onClick={() => setPage(Math.max(1, page - 1))}
            disabled={page <= 1}
            className="px-3 py-1.5 bg-slate-200 hover:bg-slate-300 dark:bg-slate-700 dark:hover:bg-slate-600 disabled:opacity-50 text-sm text-slate-700 dark:text-slate-300 rounded-lg transition-colors"
          >
            Previous
          </button>
          <span className="text-sm text-slate-500 dark:text-slate-400">
            Page {page} of {totalPages}
          </span>
          <button
            onClick={() => setPage(Math.min(totalPages, page + 1))}
            disabled={page >= totalPages}
            className="px-3 py-1.5 bg-slate-200 hover:bg-slate-300 dark:bg-slate-700 dark:hover:bg-slate-600 disabled:opacity-50 text-sm text-slate-700 dark:text-slate-300 rounded-lg transition-colors"
          >
            Next
          </button>
        </div>
      )}

      {/* Article Reader Modal */}
      {modalArticleId !== null && (
        <PressArticleModal
          articleId={modalArticleId}
          onClose={() => setModalArticleId(null)}
          onMarkRead={(id, read) => {
            markReadMutation.mutate({ id, read })
          }}
          onDelete={(id) => {
            deleteMutation.mutate(id)
          }}
        />
      )}
    </div>
  )
}
