import { useState, useCallback, useEffect } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import {
  Eye,
  Trash2,
  Send,
  RefreshCw,
  ExternalLink,
  FileText,
  Filter,
  Sparkles,
  ImageIcon,
  Maximize2,
  X,
} from 'lucide-react'
import { Header } from '../components/layout/Header'
import { Card, CardContent, Badge, Button, EmptyState, PageLoader, CopyscapeStatusBadge } from '../components/common'
import { RegenerateImageDialog, ImageLightbox } from '../components/generator'
import { endpoints, getErrorMessage } from '../api/client'
import { formatDate, formatTimeAgo, truncate } from '../utils'
import { t, tf } from '../lib/i18n'
import type { GeneratedPost, GeneratedPostStatus } from '../types'

function getStatusConfig(): Record<GeneratedPostStatus, { label: string; variant: 'success' | 'warning' | 'info' | 'error' | 'default' }> {
  return {
    published: { label: t('Published'), variant: 'success' },
    draft: { label: t('Draft'), variant: 'default' },
    pending: { label: t('Pending approval'), variant: 'warning' },
    scheduled: { label: t('Scheduled'), variant: 'info' },
    failed: { label: t('Failed'), variant: 'error' },
  }
}

type FilterStatus = 'all' | GeneratedPostStatus

export default function GeneratedContentPage() {
  const navigate = useNavigate()
  const [searchParams, setSearchParams] = useSearchParams()
  const planIdFilter = searchParams.get('planId') ? parseInt(searchParams.get('planId')!, 10) : null
  const [posts, setPosts] = useState<GeneratedPost[]>([])
  const [loading, setLoading] = useState(true)
  const [loadingMore, setLoadingMore] = useState(false)
  const [filterStatus, setFilterStatus] = useState<FilterStatus>('all')
  const [isRefreshing, setIsRefreshing] = useState(false)
  const [actionLoading, setActionLoading] = useState<number | null>(null)
  const [lightboxTarget, setLightboxTarget] = useState<GeneratedPost | null>(null)
  const [regenerateTarget, setRegenerateTarget] = useState<GeneratedPost | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(false)
  const [total, setTotal] = useState(0)
  const [statusCounts, setStatusCounts] = useState({
    total: 0, published: 0, draft: 0, pending: 0, scheduled: 0, failed: 0,
  })
  const PER_PAGE = 20

  const loadPosts = useCallback(async (pageNum: number, append = false) => {
    if (append) {
      setLoadingMore(true)
    } else {
      setLoading(true)
    }
    setError(null)
    try {
      const response = await endpoints.getGenerated({
        planId: planIdFilter || undefined,
        status: filterStatus !== 'all' ? filterStatus : undefined,
        page: pageNum,
        perPage: PER_PAGE,
      })
      const raw = response.data as any
      const items = (raw?.items ?? []) as GeneratedPost[]

      if (append) {
        setPosts(prev => [...prev, ...items])
      } else {
        setPosts(items)
      }

      setTotal(raw?.total ?? items.length)
      setHasMore(raw?.has_more ?? false)
      if (raw?.status_counts) {
        setStatusCounts(raw.status_counts)
      }
    } catch (err) {
      if (!append) setPosts([])
      setError(getErrorMessage(err, t('Failed to load')))
    } finally {
      setLoading(false)
      setLoadingMore(false)
    }
  }, [planIdFilter, filterStatus])

  useEffect(() => {
    setPage(1)
    loadPosts(1)
  }, [loadPosts])

  const handleRefresh = useCallback(async () => {
    setIsRefreshing(true)
    setPage(1)
    await loadPosts(1)
    setIsRefreshing(false)
  }, [loadPosts])

  const handleLoadMore = () => {
    const nextPage = page + 1
    setPage(nextPage)
    loadPosts(nextPage, true)
  }

  const handleDelete = async (id: number) => {
    if (!confirm(t('Delete this content?'))) return
    const deletedPost = posts.find(p => p.id === id)
    setActionLoading(id)
    try {
      await endpoints.deleteGenerated(id)
      setPosts(prev => prev.filter(p => p.id !== id))
      setTotal(prev => Math.max(0, prev - 1))
      if (deletedPost) {
        setStatusCounts(prev => {
          if (!prev) return prev
          const status = deletedPost.status || 'draft'
          return {
            ...prev,
            total: Math.max(0, (prev.total || 0) - 1),
            [status]: Math.max(0, ((prev as any)[status] || 0) - 1),
          }
        })
      }
    } catch (err) {
      setError(getErrorMessage(err, t('Failed to delete')))
    }
    setActionLoading(null)
  }

  const handlePublish = async (id: number) => {
    setActionLoading(id)
    try {
      await endpoints.publishGenerated(id)
      setPage(1)
      await loadPosts(1)
    } catch (err) {
      setError(getErrorMessage(err, t('Publish failed')))
    }
    setActionLoading(null)
  }

  const handleFilterChange = (newFilter: FilterStatus) => {
    setFilterStatus(newFilter)
  }

  if (loading && posts.length === 0) return <PageLoader />

  const statusConfig = getStatusConfig()

  return (
    <div className="min-h-screen">
      <Header
        title={t('Generated Content')}
        subtitle={tf('%d items total', statusCounts.total)}
        onRefresh={handleRefresh}
        isRefreshing={isRefreshing}
        helpContent={[
          t('Review all AI-generated articles here.'),
          t('Each article shows its Copyscape status, image, and publish state.'),
          t('Articles saved as draft can be reviewed and published manually.'),
          t('Click "Edit in WordPress" to make final adjustments before publishing.'),
        ]}
      />

      <div className="p-6">
        {/* Error banner */}
        {error && (
          <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-bc text-sm text-red-700 flex items-center justify-between">
            <span>{error}</span>
            <button onClick={() => setError(null)} className="p-0.5 text-red-400 hover:text-red-600 transition-colors">
              <X className="w-4 h-4" />
            </button>
          </div>
        )}

        {/* Stats row */}
        <div className="grid grid-cols-2 md:grid-cols-5 gap-4 mb-6">
          {([
            { label: t('Total'), value: statusCounts.total, filter: 'all' as FilterStatus, variant: 'primary' as const },
            { label: t('Published'), value: statusCounts.published, filter: 'published' as FilterStatus, variant: 'success' as const },
            { label: t('Draft'), value: statusCounts.draft, filter: 'draft' as FilterStatus, variant: 'default' as const },
            { label: t('Pending'), value: statusCounts.pending, filter: 'pending' as FilterStatus, variant: 'warning' as const },
            { label: t('Failed'), value: statusCounts.failed, filter: 'failed' as FilterStatus, variant: 'error' as const },
          ]).map(s => (
            <button
              key={s.filter}
              onClick={() => handleFilterChange(s.filter)}
              className={`p-3 rounded-bc border text-center transition-colors ${
                filterStatus === s.filter
                  ? 'border-bc-primary bg-bc-primary-light'
                  : 'border-bc-gray-200 bg-white hover:border-bc-gray-300'
              }`}
            >
              <div className="text-2xl font-bold text-bc-gray-800">{s.value}</div>
              <div className="text-xs text-bc-gray-500 mt-1">{s.label}</div>
            </button>
          ))}
        </div>

        {/* Plan filter chip */}
        {planIdFilter && (
          <div className="flex items-center gap-2 mb-4 p-3 bg-teal-50 rounded-bc border border-teal-200">
            <span className="text-sm text-bc-teal font-medium">
              {tf('Showing articles from plan #%d', planIdFilter)}
            </span>
            <button
              onClick={() => {
                searchParams.delete('planId')
                setSearchParams(searchParams)
              }}
              className="p-0.5 text-bc-gray-400 hover:text-bc-gray-600 transition-colors"
              title={t('All plans')}
            >
              <X className="w-4 h-4" />
            </button>
          </div>
        )}

        {/* Filter bar */}
        {(posts.length > 0 || filterStatus !== 'all') && (
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-2 text-sm text-bc-gray-500">
              <Filter className="w-4 h-4" />
              <span>{tf('Showing %d of %d', posts.length, total)}</span>
            </div>
            <Button variant="primary" onClick={() => navigate('/generate')}>
              <Sparkles className="w-4 h-4" />
              {t('Create new content')}
            </Button>
          </div>
        )}

        {/* Content list */}
        {posts.length === 0 ? (
          <Card>
            <CardContent>
              <EmptyState
                variant="inbox"
                title={filterStatus === 'all' && !planIdFilter ? t('No content created yet') : t('No content in current filter')}
                description={filterStatus === 'all' && !planIdFilter
                  ? t('Start creating AI content for your site')
                  : t('Try changing the filter to see other content')
                }
                action={filterStatus === 'all' && !planIdFilter ? {
                  label: t('Create Content'),
                  onClick: () => navigate('/generate'),
                } : undefined}
              />
            </CardContent>
          </Card>
        ) : (
          <div className="space-y-3">
            {posts.map(post => {
              const config = statusConfig[post.status] || statusConfig.draft
              const isActioning = actionLoading === post.id
              return (
                <Card key={post.id} padding="none">
                  <CardContent className="p-4">
                    <div className="flex items-start gap-4">
                      {/* Image thumbnail — click opens lightbox or generate dialog */}
                      {post.wp_post_id ? (
                        <button
                          onClick={() => {
                            if (post.featured_image_url) {
                              setLightboxTarget(post)
                            } else {
                              setRegenerateTarget(post)
                            }
                          }}
                          className="relative w-10 h-10 rounded-bc overflow-hidden shrink-0 mt-0.5 cursor-pointer group border border-bc-gray-200"
                          title={post.featured_image_url ? t('Expand image') : t('Generate Image')}
                        >
                          {post.featured_image_url ? (
                            <>
                              <img
                                src={post.featured_image_thumbnail || post.featured_image_url}
                                alt=""
                                className="w-full h-full object-cover"
                              />
                              <div className="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                                <Maximize2 className="w-4 h-4 text-white" />
                              </div>
                            </>
                          ) : (
                            <div className="w-full h-full bg-bc-gray-100 flex items-center justify-center group-hover:bg-bc-primary-light transition-colors">
                              <ImageIcon className="w-5 h-5 text-bc-gray-400 group-hover:text-bc-primary transition-colors" />
                            </div>
                          )}
                        </button>
                      ) : (
                        <div className="w-10 h-10 rounded-bc bg-bc-gray-100 flex items-center justify-center shrink-0 mt-0.5">
                          <FileText className="w-5 h-5 text-bc-gray-400" />
                        </div>
                      )}
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1">
                          <h3 className="font-semibold text-bc-gray-800 truncate">
                            {(post as any).title
                              || (post.generated_content
                                ? truncate(extractTitle(post.generated_content), 80)
                                : tf('Content #%d', post.id))
                            }
                          </h3>
                          <Badge variant={config.variant} dot>{config.label}</Badge>
                          <CopyscapeStatusBadge
                            status={post.copyscape_status}
                            matchPercent={post.copyscape_match}
                            sectionsRewritten={post.copyscape_rewritten}
                          />
                        </div>
                        <div className="flex items-center gap-4 text-xs text-bc-gray-500">
                          <span>{t('Type:')} {post.post_type}</span>
                          <span>{formatTimeAgo(post.created_at)}</span>
                          {post.published_at && (
                            <span>{t('Published:')} {formatDate(post.published_at)}</span>
                          )}
                          {post.plan_id && post.plan_id > 0 && (
                            <span className="text-bc-gray-400">{tf('Plan #%d', post.plan_id)}</span>
                          )}
                        </div>
                        {post.error_message && (
                          <p className="text-xs text-red-600 mt-1">{post.error_message}</p>
                        )}
                      </div>
                      <div className="flex items-center gap-1 shrink-0">
                        {post.wp_post_id && (
                          <a
                            href={`${window.bmaiSettings?.adminUrl || '/wp-admin/'}post.php?post=${post.wp_post_id}&action=edit`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="p-2 text-bc-gray-400 hover:text-bc-primary transition-colors"
                            title={t('Edit in WordPress')}
                          >
                            <ExternalLink className="w-4 h-4" />
                          </a>
                        )}
                        {post.wp_post_id && (
                          <a
                            href={`${window.bmaiSettings?.homeUrl || '/'}?p=${post.wp_post_id}&preview=true`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="p-2 text-bc-gray-400 hover:text-bc-primary transition-colors"
                            title={t('Preview on site')}
                          >
                            <Eye className="w-4 h-4" />
                          </a>
                        )}
                        {(post.status === 'draft' || post.status === 'pending') && (
                          <button
                            onClick={() => handlePublish(post.id)}
                            disabled={isActioning}
                            className="p-2 text-bc-gray-400 hover:text-green-600 transition-colors disabled:opacity-50"
                            title={t('Publish')}
                          >
                            {isActioning ? <RefreshCw className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
                          </button>
                        )}
                        <button
                          onClick={() => handleDelete(post.id)}
                          disabled={isActioning}
                          className="p-2 text-bc-gray-400 hover:text-red-600 transition-colors disabled:opacity-50"
                          title={t('Delete')}
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )
            })}

            {/* Load More */}
            {hasMore && (
              <div className="text-center mt-4">
                <Button variant="secondary" onClick={handleLoadMore} loading={loadingMore}>
                  {total - posts.length > 0
                    ? tf('Load more (%d remaining)', total - posts.length)
                    : t('Load more')
                  }
                </Button>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Image Lightbox */}
      {lightboxTarget?.featured_image_url && (
        <ImageLightbox
          imageUrl={lightboxTarget.featured_image_url}
          postTitle={
            (lightboxTarget as any).title
            || (lightboxTarget.generated_content
              ? extractTitle(lightboxTarget.generated_content as string | Record<string, unknown>)
              : '')
          }
          isOpen={!!lightboxTarget}
          onClose={() => setLightboxTarget(null)}
          onRegenerate={() => {
            setLightboxTarget(null)
            setRegenerateTarget(lightboxTarget)
          }}
        />
      )}

      {/* Regenerate Image Dialog */}
      {regenerateTarget?.wp_post_id && (
        <RegenerateImageDialog
          postId={regenerateTarget.wp_post_id}
          postTitle={
            (regenerateTarget as any).title
            || (regenerateTarget.generated_content
              ? extractTitle(regenerateTarget.generated_content as string | Record<string, unknown>)
              : '')
          }
          currentImageUrl={regenerateTarget.featured_image_url}
          isOpen={!!regenerateTarget}
          onClose={() => setRegenerateTarget(null)}
          onSuccess={(newUrl, thumbUrl) => {
            setPosts(prev =>
              prev.map(p =>
                p.id === regenerateTarget.id
                  ? { ...p, featured_image_url: newUrl, featured_image_thumbnail: thumbUrl || newUrl }
                  : p
              )
            )
            setRegenerateTarget(null)
          }}
        />
      )}
    </div>
  )
}

function extractTitle(raw: string | Record<string, unknown>): string {
  if (typeof raw === 'object' && raw !== null) {
    if (raw.title) return String(raw.title)
    const content = raw.content as string | undefined
    if (content) return extractTitle(content)
    return ''
  }
  const html = raw as string
  const match = html.match(/<h[12][^>]*>(.*?)<\/h[12]>/i)
  if (match) return match[1].replace(/<[^>]+>/g, '')
  const textMatch = html.replace(/<[^>]+>/g, ' ').trim()
  return textMatch.slice(0, 100)
}
