/**
 * BoostMedia AI Content Generator Admin - Review Step
 *
 * @package BoostMedia_AI
 * @license GPL-2.0-or-later
 */

import { useState } from 'react'
import {
  ChevronRight,
  ChevronDown,
  ChevronUp,
  Check,
  Clock,
  Send,
  RotateCcw,
  CheckCheck,
  ExternalLink,
  Eye,
  Trash2,
  RefreshCw,
  ImageIcon,
  Maximize2,
} from 'lucide-react'
import type { GeneratedPost } from '../../types'
import { Button, Card, Badge, CopyscapeStatusBadge } from '../common'
import { GeneratedPostPreview } from './GeneratedPostPreview'
import { RegenerateImageDialog } from './RegenerateImageDialog'
import { ImageLightbox } from './ImageLightbox'
import { endpoints } from '../../api/client'
import { t, tf, isRtl } from '../../lib/i18n'

type PostStatus = GeneratedPost['status']

function getStatusConfig(): Record<PostStatus, { 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' },
  }
}

interface ReviewStepProps {
  posts: GeneratedPost[]
  onPublish: (postIds: number[]) => void
  onSchedule: (postIds: number[], scheduleAt: string) => void
  onBack: () => void
  onStartOver: () => void
}

export function ReviewStep({
  posts,
  onPublish,
  onSchedule,
  onBack,
  onStartOver,
}: ReviewStepProps) {
  const safePosts = Array.isArray(posts) ? posts : []
  const [selectedPosts, setSelectedPosts] = useState<Set<number>>(
    new Set(safePosts.map((p) => p.id))
  )
  const [expandedPost, setExpandedPost] = useState<number | null>(null)
  const [lightboxTarget, setLightboxTarget] = useState<GeneratedPost | null>(null)
  const [regenerateTarget, setRegenerateTarget] = useState<GeneratedPost | null>(null)
  const [localPosts, setLocalPosts] = useState<GeneratedPost[]>(safePosts)
  const [isPublishing, setIsPublishing] = useState(false)
  const [actionLoading, setActionLoading] = useState<number | null>(null)
  const [publishResult, setPublishResult] = useState<{
    success: number
    failed: number
  } | null>(null)

  const togglePostSelection = (postId: number) => {
    const newSelected = new Set(selectedPosts)
    if (newSelected.has(postId)) {
      newSelected.delete(postId)
    } else {
      newSelected.add(postId)
    }
    setSelectedPosts(newSelected)
  }

  const selectAll = () => {
    setSelectedPosts(new Set(localPosts.map((p) => p.id)))
  }

  const deselectAll = () => {
    setSelectedPosts(new Set())
  }

  const handlePublishSingle = async (postId: number) => {
    setActionLoading(postId)
    try {
      await endpoints.publishGenerated(postId)
      setLocalPosts((prev) =>
        prev.map((p) =>
          p.id === postId ? { ...p, status: 'published' as const } : p
        )
      )
    } catch (err) {
      console.error(`Failed to publish post ${postId}:`, err)
    }
    setActionLoading(null)
  }

  const handleDeleteSingle = async (postId: number) => {
    if (!confirm(t('Delete this content?'))) return
    setActionLoading(postId)
    try {
      await endpoints.deleteGenerated(postId)
      setLocalPosts((prev) => prev.filter((p) => p.id !== postId))
      setSelectedPosts((prev) => {
        const next = new Set(prev)
        next.delete(postId)
        return next
      })
    } catch (err) {
      console.error(`Failed to delete post ${postId}:`, err)
    }
    setActionLoading(null)
  }

  const handlePublishBulk = async () => {
    setIsPublishing(true)
    setPublishResult(null)

    let success = 0
    let failed = 0

    for (const postId of selectedPosts) {
      try {
        await endpoints.publishGenerated(postId)
        success++
        setLocalPosts((prev) =>
          prev.map((p) =>
            p.id === postId ? { ...p, status: 'published' as const } : p
          )
        )
      } catch (err) {
        console.error(`Failed to publish post ${postId}:`, err)
        failed++
      }
    }

    setPublishResult({ success, failed })
    setIsPublishing(false)
    setSelectedPosts(new Set())

    if (success > 0) {
      onPublish(Array.from(selectedPosts))
    }
  }

  const handleSchedule = async () => {
    const tomorrow = new Date()
    tomorrow.setDate(tomorrow.getDate() + 1)
    tomorrow.setHours(9, 0, 0, 0)

    setIsPublishing(true)

    for (const postId of selectedPosts) {
      try {
        await endpoints.scheduleGenerated(postId, tomorrow.toISOString())
        setLocalPosts((prev) =>
          prev.map((p) =>
            p.id === postId
              ? { ...p, status: 'scheduled' as const, scheduled_at: tomorrow.toISOString() }
              : p
          )
        )
      } catch (err) {
        console.error(`Failed to schedule post ${postId}:`, err)
      }
    }

    setIsPublishing(false)
    onSchedule(Array.from(selectedPosts), tomorrow.toISOString())
  }

  const statusConfig = getStatusConfig()

  return (
    <div className="max-w-4xl mx-auto">
      <div className="text-center mb-8">
        <h2 className="text-2xl font-bold text-bc-gray-800 mb-2">
          {t('Content Review')}
        </h2>
        <p className="text-bc-gray-500">
          {t('Review the created content, edit if needed, and approve for publishing')}
        </p>
      </div>

      {/* Success/Error Message */}
      {publishResult && (
        <Card
          className={`mb-6 ${
            publishResult.failed > 0 ? 'bg-yellow-50' : 'bg-green-50'
          }`}
        >
          <div className="flex items-center gap-3">
            <CheckCheck
              className={`w-6 h-6 ${
                publishResult.failed > 0 ? 'text-yellow-600' : 'text-bc-success'
              }`}
            />
            <div>
              <p className="font-semibold text-bc-gray-800">
                {publishResult.success > 0 &&
                  tf('%d posts published successfully', publishResult.success)}
                {publishResult.failed > 0 && publishResult.success > 0 && ', '}
                {publishResult.failed > 0 &&
                  tf('%d posts failed', publishResult.failed)}
              </p>
            </div>
          </div>
        </Card>
      )}

      {/* Selection Controls */}
      <Card className="mb-6">
        <div className="flex items-center justify-between flex-wrap gap-3">
          <div className="flex items-center gap-4">
            <span className="font-medium text-bc-gray-700">
              {tf('%d of %d selected', selectedPosts.size, localPosts.length)}
            </span>
            <div className="flex gap-2">
              <button
                onClick={selectAll}
                className="text-sm text-bc-primary hover:underline"
              >
                {t('Select all')}
              </button>
              <span className="text-bc-gray-300">|</span>
              <button
                onClick={deselectAll}
                className="text-sm text-bc-primary hover:underline"
              >
                {t('Deselect all')}
              </button>
            </div>
          </div>

          <div className="flex gap-2">
            <Button
              variant="secondary"
              size="sm"
              onClick={handleSchedule}
              disabled={selectedPosts.size === 0 || isPublishing}
              icon={<Clock className="w-4 h-4" />}
            >
              {t('Schedule')}
            </Button>
            <Button
              size="sm"
              onClick={handlePublishBulk}
              disabled={selectedPosts.size === 0 || isPublishing}
              loading={isPublishing}
              icon={<Send className="w-4 h-4" />}
            >
              {t('Publish now')}
            </Button>
          </div>
        </div>
      </Card>

      {/* Posts List */}
      <div className="space-y-4 mb-8">
        {localPosts.map((post) => {
          const config = statusConfig[post.status] || statusConfig.draft
          const isActioning = actionLoading === post.id
          const isExpanded = expandedPost === post.id

          return (
            <Card key={post.id} padding="none" className="overflow-hidden">
              {/* Post header row */}
              <div className="p-4 flex items-start gap-4">
                {/* Checkbox */}
                <div className="shrink-0 pt-0.5">
                  <label className="flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      checked={selectedPosts.has(post.id)}
                      onChange={() => togglePostSelection(post.id)}
                      className="w-5 h-5 rounded border-bc-gray-300 text-bc-primary focus:ring-bc-primary focus:ring-2"
                    />
                  </label>
                </div>

                {/* 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">
                    <ImageIcon className="w-5 h-5 text-bc-gray-400" />
                  </div>
                )}

                {/* Post info */}
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-1 flex-wrap">
                    <h3
                      className="font-semibold text-bc-gray-800 truncate cursor-pointer hover:text-bc-primary transition-colors"
                      onClick={() => setExpandedPost(isExpanded ? null : post.id)}
                    >
                      {extractTitle(post) || 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>{t('created')} {new Date(post.created_at).toLocaleDateString()}</span>
                    {post.error_message && (
                      <span className="text-red-600">{post.error_message}</span>
                    )}
                  </div>
                </div>

                {/* Action buttons */}
                <div className="flex items-center gap-1 shrink-0">
                  {/* Edit in WordPress */}
                  {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>
                  )}

                  {/* Preview on site */}
                  {post.wp_post_id && (
                    <a
                      href={`/?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>
                  )}

                  {/* Publish single post */}
                  {(post.status === 'draft' || post.status === 'pending') && (
                    <button
                      onClick={() => handlePublishSingle(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>
                  )}

                  {/* Delete */}
                  <button
                    onClick={() => handleDeleteSingle(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>

                  {/* Expand/collapse toggle — chevron instead of eye */}
                  <button
                    onClick={() => setExpandedPost(isExpanded ? null : post.id)}
                    className="p-2 text-bc-gray-400 hover:text-bc-primary transition-colors"
                    title={isExpanded ? t('Collapse') : t('Expand')}
                  >
                    {isExpanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
                  </button>
                </div>
              </div>

              {/* Expandable preview content */}
              {isExpanded && (
                <div className="border-t border-bc-gray-200">
                  <GeneratedPostPreview
                    post={post}
                    isExpanded={true}
                    onToggleExpand={() => setExpandedPost(null)}
                    hideHeader
                  />
                </div>
              )}
            </Card>
          )
        })}
      </div>

      {/* Navigation */}
      <div className="flex justify-between">
        <Button
          variant="ghost"
          onClick={onBack}
          icon={<ChevronRight className="w-5 h-5 ltr:rotate-180" />}
          iconPosition={isRtl() ? 'end' : 'start'}
        >
          {t('Back')}
        </Button>

        <div className="flex gap-3">
          <Button
            variant="secondary"
            onClick={onStartOver}
            icon={<RotateCcw className="w-5 h-5" />}
          >
            {t('Start over')}
          </Button>
          <Button
            onClick={handlePublishBulk}
            disabled={selectedPosts.size === 0 || isPublishing}
            loading={isPublishing}
            size="lg"
            icon={<Check className="w-5 h-5" />}
          >
            {t('Publish')} {selectedPosts.size > 0 && `(${selectedPosts.size})`}
          </Button>
        </div>
      </div>

      {/* Image Lightbox */}
      {lightboxTarget?.featured_image_url && (
        <ImageLightbox
          imageUrl={lightboxTarget.featured_image_url}
          postTitle={extractTitle(lightboxTarget)}
          isOpen={!!lightboxTarget}
          onClose={() => setLightboxTarget(null)}
          onRegenerate={() => {
            setLightboxTarget(null)
            setRegenerateTarget(lightboxTarget)
          }}
        />
      )}

      {/* Regenerate Image Dialog */}
      {regenerateTarget?.wp_post_id && (
        <RegenerateImageDialog
          postId={regenerateTarget.wp_post_id}
          postTitle={extractTitle(regenerateTarget)}
          currentImageUrl={regenerateTarget.featured_image_url}
          isOpen={!!regenerateTarget}
          onClose={() => setRegenerateTarget(null)}
          onSuccess={(newUrl, thumbUrl) => {
            setLocalPosts(prev =>
              prev.map(p =>
                p.id === regenerateTarget.id
                  ? { ...p, featured_image_url: newUrl, featured_image_thumbnail: thumbUrl || newUrl }
                  : p
              )
            )
            setRegenerateTarget(null)
          }}
        />
      )}
    </div>
  )
}

function extractTitle(post: GeneratedPost): string {
  if (post.title) return post.title
  const raw = post.generated_content ?? post.content
  if (typeof raw === 'object' && raw !== null) {
    if ((raw as Record<string, unknown>).title) return String((raw as Record<string, unknown>).title)
    const content = (raw as Record<string, unknown>).content as string | undefined
    if (content) return extractTitleFromHtml(content)
    return ''
  }
  if (typeof raw === 'string') return extractTitleFromHtml(raw)
  return ''
}

function extractTitleFromHtml(html: string): string {
  const match = html.match(/<h[12][^>]*>(.*?)<\/h[12]>/i)
  if (match) return match[1].replace(/<[^>]+>/g, '')
  const text = html.replace(/<[^>]+>/g, ' ').trim()
  return text.slice(0, 100)
}
