/**
 * BoostMedia AI Content Generator Admin - Generated Post Preview
 *
 * @package BoostMedia_AI
 * @license GPL-2.0-or-later
 */

import { Eye, FileText, Tag, Settings } from 'lucide-react'
import type { GeneratedPost } from '../../types'
import { Card, Badge } from '../common'
import { t, getDateLocale } from '../../lib/i18n'

interface GeneratedPostPreviewProps {
  post: GeneratedPost
  isExpanded?: boolean
  onToggleExpand?: () => void
  hideHeader?: boolean
}

export function GeneratedPostPreview({
  post,
  isExpanded = false,
  onToggleExpand,
  hideHeader = false,
}: GeneratedPostPreviewProps) {
  let content: {
    title?: string
    content?: string
    excerpt?: string
    meta_fields?: Record<string, unknown>
    seo?: { meta_title?: string; meta_description?: string; focus_keyword?: string }
  } = {}

  const raw = post.generated_content ?? post.content
  if (typeof raw === 'object' && raw !== null) {
    content = raw as typeof content
  } else if (typeof raw === 'string') {
    try {
      content = JSON.parse(raw || '{}')
    } catch {
      content = { content: raw }
    }
  }

  if (!content.title && post.title) {
    content.title = post.title
  }
  if (!content.excerpt && post.excerpt) {
    content.excerpt = post.excerpt
  }

  const statusBadgeVariant: Record<string, 'success' | 'warning' | 'error' | 'info'> = {
    draft: 'info',
    pending: 'warning',
    scheduled: 'warning',
    published: 'success',
    failed: 'error',
  }

  const statusLabels: Record<string, string> = {
    draft: t('Draft'),
    pending: t('Pending'),
    scheduled: t('Scheduled'),
    published: t('Published'),
    failed: t('Failed'),
  }

  const expandedContent = (
    <>
      {/* Excerpt */}
      {content.excerpt && (
        <div className="p-4 border-b border-bc-gray-100">
          <p className="text-sm text-bc-gray-600 font-medium mb-1">
            {t('Excerpt')}
          </p>
          <p className="text-bc-gray-700">{content.excerpt}</p>
        </div>
      )}

      {/* Content Preview */}
      <div className="p-4 border-b border-bc-gray-100">
        <p className="text-sm text-bc-gray-600 font-medium mb-2">
          {t('Content')}
        </p>
        <div
          className="
            prose prose-sm max-w-none
            text-bc-gray-700 line-clamp-6
          "
          dangerouslySetInnerHTML={{
            __html: content.content || `<p>${t('No content')}</p>`,
          }}
        />
      </div>

      {/* Meta Fields */}
      {content.meta_fields && Object.keys(content.meta_fields).length > 0 && (
        <div className="p-4 border-b border-bc-gray-100">
          <div className="flex items-center gap-2 mb-3">
            <Settings className="w-4 h-4 text-bc-gray-500" />
            <p className="text-sm text-bc-gray-600 font-medium">
              {t('Custom fields')}
            </p>
          </div>
          <div className="grid grid-cols-2 gap-3">
            {Object.entries(content.meta_fields).map(([key, value]) => (
              <div
                key={key}
                className="bg-bc-gray-50 rounded-bc p-3"
              >
                <p className="text-xs text-bc-gray-500 mb-1">{key}</p>
                <p className="text-sm text-bc-gray-700 truncate">
                  {typeof value === 'string'
                    ? value
                    : JSON.stringify(value)}
                </p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* SEO */}
      {content.seo && (
        <div className="p-4 bg-bc-gray-50">
          <div className="flex items-center gap-2 mb-3">
            <Tag className="w-4 h-4 text-bc-gray-500" />
            <p className="text-sm text-bc-gray-600 font-medium">SEO</p>
          </div>
          <div className="space-y-2">
            {content.seo.focus_keyword && (
              <div>
                <p className="text-xs text-bc-gray-500">{t('Focus Keyword')}</p>
                <p className="text-sm text-bc-primary font-medium">
                  {content.seo.focus_keyword}
                </p>
              </div>
            )}
            {content.seo.meta_title && (
              <div>
                <p className="text-xs text-bc-gray-500">{t('SEO Title')}</p>
                <p className="text-sm text-bc-gray-700">
                  {content.seo.meta_title}
                </p>
              </div>
            )}
            {content.seo.meta_description && (
              <div>
                <p className="text-xs text-bc-gray-500">{t('SEO Description')}</p>
                <p className="text-sm text-bc-gray-700">
                  {content.seo.meta_description}
                </p>
              </div>
            )}
          </div>
        </div>
      )}
    </>
  )

  if (hideHeader) {
    return isExpanded ? <div>{expandedContent}</div> : null
  }

  return (
    <Card
      padding="none"
      className={`
        overflow-hidden transition-all duration-300
        ${isExpanded ? 'ring-2 ring-bc-primary' : ''}
      `}
    >
      {/* Header */}
      <div
        onClick={onToggleExpand}
        className="
          flex items-center justify-between p-4 cursor-pointer
          hover:bg-bc-gray-50 transition-colors duration-150
        "
      >
        <div className="flex items-center gap-4">
          <div className="p-2 bg-bc-primary-light rounded-bc">
            <FileText className="w-5 h-5 text-bc-primary" />
          </div>
          <div>
            <h3 className="font-semibold text-bc-gray-800 line-clamp-1">
              {content.title || t('No title')}
            </h3>
            <p className="text-sm text-bc-gray-500 mt-0.5">
              {post.post_type} • {t('created')}{' '}
              {new Date(post.created_at).toLocaleDateString(getDateLocale())}
            </p>
          </div>
        </div>

        <div className="flex items-center gap-3">
          <Badge variant={statusBadgeVariant[post.status] || 'info'}>
            {statusLabels[post.status] || post.status}
          </Badge>
          <button
            className="p-2 text-bc-gray-400 hover:text-bc-primary transition-colors"
            aria-label={isExpanded ? t('Close preview') : t('Open preview')}
          >
            <Eye className="w-5 h-5" />
          </button>
        </div>
      </div>

      {/* Expanded Content */}
      {isExpanded && (
        <div className="border-t border-bc-gray-200">
          {expandedContent}
        </div>
      )}
    </Card>
  )
}
